I have a range from a min to a maximum.
I want to generate a set of information via calculation for each of these values.
I want to output this information via print.
How do I generate this output given a loop will only output information for 1 value of the range at a time?
Programming experience – absolute beginner.
Here’s the code:
Basically, if the user enters 1, I output information for all values of min2.
else, I output only the set of min2 and their information whose probB is 1/2.
Also, can I just use min1 (which comes from user input) without assigning it to min2?
int prompt = Integer.parseInt(input); // user input
int min2 = 0;
double probB = 0;
for (min2 = min1; min2 < max1; min2++) // for loop
{
if (prompt==1){
int R = 0;
double Rlow = 0;
double Rhigh = 0;
R = (int) (Math.sqrt(2) + 1)*min2;
Rlow = (Math.sqrt(2)+1)*min2+ 1;
Rhigh = (Math.sqrt(2)+1)*min2;
System.out.println(min2);
System.out.print(""+Rlow+""+Rhigh);
System.out.println(R);
probB = (R/R+min2)*(R-1/R+min2-1);
System.out.println(probB);
}
else {
int R = 0;
double Rlow = 0;
double Rhigh = 0;
R = (int) (Math.sqrt(2) + 1)*min2;
Rlow = (Math.sqrt(2)+1)*min2+ 1;
Rhigh = (Math.sqrt(2)+1)*min2;
probB = (R/R+min2)*(R-1/R+min2-1);
if (probB == 1/2){
System.out.println(min2);
System.out.println(""+Rlow+""+Rhigh);
System.out.println(R);
System.out.println(probB);
}
}
}
Instead of
use
the expression
1/2is calculated as an integer, and its value is zero. Even better:Note however that if there’s any rounding in the calculation of
probBthe result might not end up being exactly 0.5 even when you expect it to. You can construct expressions where the end result ‘should’ be 0.5 but the actual result is very close to but not exactly 0.5, due to inaccuracies in floating point representations. Your best bet is to do something like:I.e. close to one part in 10^10
Floating point calculations are very useful, but they come with some gotchas due to the fact that they’re not exact representations. In decimal, there’s a whole set of rational numbers that cannot be expressed exactly, such as 1/3, 1/7, etc. You can get arbitrarily close by extending the number of digits (0.33333333… or 0.142857142857142…) but you can’t write an exact representation in decimal. The same thing happens in floating point (for a different set of numbers), but FP has a fixed length, so a number like 0.1 cannot be expressed exactly in FP. It’s close, but not exact. You must always allow for that possibility in comparisons.