Java While loop extra conditions - java

In JavaScript you can add extra conditions like:
var b = 0.0;
var q = (void 0);
var e = -1.0;
while(q = e, b > 32.0){
console.log(q);
b++;
}
Meaning that q equals to e.
I have tried to rephrase Java code to
Float b = 0.0;
Float q = Float.NaN;
Float e = -1.0;
do{
q = e;
b++;
}while(b < 32.0);
But it seems that it doesn't work as JS version.
Can I just add q = e to while conditions? Is there any valid Java syntax for it?

There is no comma operator in Java, and even if there was, it would be considered bad style.
There are ways you can achieve similar things. If you define a function that takes any parameter and always returns true:
<T> boolean trick(T any) {
return true;
}
you can use it to sneak in assignment expressions in any boolean context you want:
while (trick(q = e) && b > 32.0){
System.out.println(q);
b++;
}
But again, this would be considered terrible style. Don't use this in a real project.

Java doesn't have a hyperflexible comma operator like JavaScript so you'll have to split the statements apart. That's not a bad thing. while(q = e, b > 32.0) is poor style.
Stick with a regular while loop. A do-while loop won't do because it'll always execute b++ at least once.
I would use double rather than float.
double b = 0.0;
double q;
double e = -1.0;
q = e;
while (b < 32.0) {
b++;
q = e;
}
And we might as well initialize q when it's declared:
double b = 0.0;
double e = -1.0;
double q = e;
while (b < 32.0) {
b++;
q = e;
}

Related

Accuracy with very small probabilities

I writing a program in Java which requires me to compute some probabilities, and for larger inputs, the probabilities can eventually become very small. Therefore, to prevent underflow issues, I would like to take the log probabilities instead.
I am, however, having trouble implementing this. At each stage of computation there can be a different number of options, to which probabilities need to be assigned, and each stage they need to add up to 1. The probabilities are based on a number of different variables. I take a sum over all possibilities using the following formula:
Math.pow(d[i], a) * Math.pow(1/c[i], b)
This gives me a variable, total. To then establish the probability p_i,
p_i = (Math.pow(d[i], a) * Math.pow(1/c[i], b)) / total
My question is, how can I implement this using log probabilities, so that I do not get 'Infinity' and 'NaN' values, since these are what I have been getting so far.
What I think you should try is to use Kahan Summation. It will allow to sum properly not loosing precision.
In some C-like pseudo-code (sorry, my Java is rusty, code is untested)
double total(int N, double[] d, double[] c, double a, double b) {
double sum = 0.0;
double running_error = 0.0;
for (int i = 0; i != N; ++i) {
if (d[i] == 0.0)
continue;
if (c[i] == 0.0)
throw "XXX"; // some error reporting
double v = 0.0;
if (d[i] > 0.0 && c[i] > 0.0) {
// using log trick, if you want
double lpi = a*Math.log(d[i]) - b*Math.log(c[i]);
v = Math.exp(lpi);
}
else {
v = Math.pow(d[i], a) * Math.pow(1.0/c[i], b);
}
double difference = v - running_error;
double temp = sum + difference;
running_error = (temp - sum) - difference;
sum = temp;
}
return sum;
}

How to get the goldenRatio using recursion in Java?

I'm working on this simple java recursion problem given the following directions:
Calculate the golden ratio.
Given two numbers a and b with a > b > 0, the ratio is b / a.
I have done some code but I'm stuck on getting the recursion working properly. Here's my code:
public class MyTesting {
public static void main(String[] args) {
System.out.println(ratio(8 , 4));
}
public static double ratio(int a, int b) {
int goldelRatio = 0;
if(a > b && b > 0){
return goldelRatio = a / b;
}
return goldelRatio;
}
}
How about something like this:
double goldenRatio(double a, double b, double epsilon) {
if(Math.abs((b / a) - ((a + b) / b)) < epsilon) {
return ((a + b) / b);
} else {
return goldenRatio(b, a + b, epsilon);
}
}
This way you achieve what you need in one function, with epsilon deciding how fine the resolution would be.
Also as an added bonus, and although Java doesn't have (at the time of writing this at least) tail recursion optimization, in theory this function could be optimized by tail recursion.
example with hard coded epsilon:
double goldenRatio(double a, double b) {
double epsilon = 0.00001;
if(Math.abs((b / a) - ((a + b) / b)) < epsilon) {
return ((a + b) / b);
} else {
return goldenRatio(b, a + b);
}
}
example run:
public static void main(String[] args) {
double goldenRation1 = goldenRatio(1.0, 1.0);
System.out.println(goldenRation1); // prints 1.618032786885246
System.out.println(goldenRation1 > 1.61800 && goldenRation1 < 1.61806); // prints true
double goldenRation2 = goldenRatio(100.0, 6.0);
System.out.println(goldenRation2); // prints 1.6180367504835589
System.out.println(goldenRation2 > 1.61800 && goldenRation2 < 1.61806); // prints true
}
Yours is not a recursive function, a recursive function that calculates Golden Ratio would look like the one below.
private int MAX_COUNTER = 50;
private int count = 0;
public double ratio(double a, double b) {
count++;
double goldenRatio = b / a;
if (count < MAX_COUNTER) {
return ratio(b, a + b);
}
return goldenRatio;
}
NOTE: I put the counters because given that is a recursive function trying to find a number with infinite decimals, it will cause the JVM to go on StackOverflow :) , so we got to stop it sooner or later.
Recursion mainly means methods calling themself, meaning you should try something like that:
public double recursionMethod(int a, int b){
int c = a+b;
if(Math.abs(ratio(b,a)-ratio(c,b))< (double) 1/42)
return ratio(c,b);
else
return recursionMethod(b,c);
}
1/42 is just your accuracy, you can implement any other breaking condition you like. Call this method in main with arguments (1,1).

Passing variables through if statements without new method

So well I'm just here wondering if there's a way to pass a variable through a statement. Something like this:
if (a < b) {
double g = 1
} else if (a > b) {
double g = 0
}
if (g = 1) {
System.out.print("true");
} else {
System.out.print("false");
}
Mainly saying, I want to set a variable if a statement is true or not, go to the next section of code and print out "true" or "false" and I pretty much am just wondering if this is possible without creating a new method (and of course if there is code for it).
Thank you.
You are almost there. You have to declare g outside the if statements, so you can access to it whithin the whole function. Read more about scopes, if you declare a variable inside a block {}, it will be accessible just inside it, so when you declared it into the if-else if blocks, you couldn't access to the variable outside.
Also to compare a primitive type (in this case double) you have to use == operator, because = is used for assignment.
double g;
if (a<b) {
g = 1;
}
else if (a>b) {
g = 0;
}
// What happen if 'a = b'?
if (g == 1) {
System.out.print("true");
}
else {
System.out.print("false");
}
Note: What value will take g if a == b? You may want to take care about that case too.
double g;
if (a<b) {
g=1
}
else if (a>b) {
g=0
}
if (g==1) {
System.out.print("true");
}
else {
System.out.print("false");
}
also make sure that you always use == instead of = in your if-statement
The if condition if (g=1) does not work with java. This would work with C though.
You should code if (g==1) to test if g is in fact equal to the int value 1.
You've got three problems.
a and b aren't defined. Define them before entering the if statement.
Define g outside of the if statement (a simple double g; will suffice), then set the values as part of your conditional logic. You do have to give it a default value if you intend to keep the else if there, since Java would complain about that not being defined.
g=1 isn't going to work the way you think it should; you probably mean g == 1.
With else if
int a, b; // assumed instantiated with values
double g = -1; // required since Java can't guarantee that the else-if will be hit
if (a<b) {
g = 1;
} else if (a>b) {
g = 0;
}
With else
int a, b; // assumed instantiated with values
double g; // instantiation not required since Java can guarantee the else case
if (a<b) {
g = 1;
} else {
g = 0;
}
double g; double a = 4.0; double b = 3.0;
if(a < b){
g = 1.0;
System.out.print("true");
}
else if (a > b){
g = 0.0;
System.out.print("false");
}
// Why not write your code like the above example. It seems like the
//same operations are executed but with less lines of code.

Difference between operator += and =+

Can you clearly explain the difference between the operator += and the operator =+ ?
Obviously, both are shortcuts for a sum, but I don't get the meaning of "=+"
a += b is equivalent to a = a + b. But what is the equivalence of a =+ b ???
Here is the practical example:
public class SumOfSquares {
private int[] inputArray;
private Integer result;
public SumOfSquares(int[] inputArray) {
this.inputArray=inputArray;
result = new Integer(0);
}
public Integer getResult () {
for (int counter=0; counter<inputArray.length; counter++) {
int currentNumber = inputArray[counter];
result += currentNumber*currentNumber;
}
return result;
}
}
inputArray={1,2,3,4,5}. Expected result=55 (1^2+2^2+3^2+4^2+5^2 = 1+4+9+16+25 = 55)
If I replace result += currentNumber*currentNumber; by result =+ currentNumber*currentNumber;, I get a result of 25 instead of 55. I would like to understand why.
=+ is not an operator. You might be confusing it with the combination of the assignment = and the unary + operator, which will take the value as positive (doesn't change its sign, + (-3) is still -3) and can be perfectly ommitted for integer values.
int a = 5;
int b = 3;
a = (+b); // a = 3
a = (-b); // a = -3
&plus; Unary plus operator; indicates positive value (numbers are positive without this, however)
a=+b is the same as a=0+b, in other words, a=b
=+ is not an operator. it is the assignment operator =, followed by a positive sign +. The + is applied to the variable to the right, so you can read it as a= (+b).
a -= b is equivalent to a = a - b, and
a =- b is equivalent to a = - b
No, both are not shortcuts for a sum. Have you tried =+ to see what it does?
Hint, try with =- to see what that does.

Flow analysis in javac - variable a might not have been initialized

In the following code I'd expect that it should not be necessary to initialise variables a and b in last else block, however the compiler does not like it.
import java.util.Random;
public class Foo {
private void foo () {
double a,b;
boolean c;
double r = (new Random()).nextDouble();
if(r < 0.25) {
a = 1;
b = 2;
c = true;
} else if(r >= 0.25 && r < 0.75) {
a = 3;
b = 3;
c = true;
} else {
// why is it necessary to init a and b here?
// given that c is set to false
c = false;
}
if(c) {
double k = a + b;
}
}
}
With the code above, the compiler does complain.
bash-3.2$ javac Foo.java
Foo.java:25: variable a might not have been initialized
double k = a + b;
^
Foo.java:25: variable b might not have been initialized
double k = a + b;
^
2 errors
I would have thought that the compiler could do the static analysis to figure out that k will not be evaluated if c is set to false. So my question is why does the compiler demand that I initialise a and b?
The compiler isn't smart enough to understand that going through the else block will set c to false, and that the next if block thus won't ever be executed. The static analysis is more limited than what you expect, which also makes the comilation faster/
And it's probably a good thing, because changing the code of the else block would suddenly make the next if block not compilable, which would be annoying.

Categories

Resources