Reputation: 563
The output for a Java program I wrote is giving me "Infinity" when I should be getting a number. I'm using floats, and I don't think my numbers are going out of the range of what floats can handle.
My question is would I ever get "Infinity" as the output if Java computes a value that is bigger than what the data type in use can handle? Or is "Infinity" only returned if I have accidentally divided by zero somewhere.
Upvotes: 3
Views: 10189
Reputation: 353
Yes, according to this: Maximum value for Float in Java? the max value a float can have is Float.MAX_VALUE.
You might want to do some simple checks with the debugger where ever you're dividing this float value. Alternatively, you could sprinkle your code with log statements.
There's a class called StackTraceElement that's provided by the Thread class. You could use that to see which class/line number.
https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#getStackTrace() https://docs.oracle.com/javase/7/docs/api/java/lang/StackTraceElement.html
Say you have something like this:
float result = A / B;
Anytime you see something like this, you could use this simple print statement:
float result = A / B;
System.out.format("Divisor: %d, Dividend: %d, result: %d", A, B, result);
// alternatively, add in the stack trace stuff.
Once you find the culprit, the cause is probably pretty obvious. My thoughts are that you might be initializing this 'B' value to 0, but never setting it to the float you actually intend to divide by.
Upvotes: 2
Reputation: 12347
The JLS answers this pretty explicitly.
A floating-point operation that overflows produces a signed infinity.
You are probably dividing by zero somewhere but you could check.
double b = 1.1*Double.MAX_VALUE;
System.out.println(b);
That shows up as infinity.
Upvotes: 7
Reputation: 51
Please refer to thedayofcondor's answer here: What are the INFINITY constants in Java, really?
When your operations leave the range of float, you DO get infinity as a result, by default. As you said, however, infinity usually begins with a zero division somewhere, or with a cyclic (or too large of a) operation. If you post a snippet of your code i can give you a hint on where it's 'unprotected'.
Operation Result
n ÷ ± Infinity 0
±Infinity × ±Infinity ±Infinity
±nonzero ÷ 0 ±Infinity
Infinity + Infinity Infinity
±0 ÷ ±0 NaN
Infinity - Infinity NaN
±Infinity ÷ ±Infinity NaN
±Infinity × 0 NaN
Upvotes: 2