Is it possible to get a floating point error in this case?

I know that floating point arithmetic is complex, but I'm not sure if you can get an error if you have a division followed by back multiplication. It is possible, written in the code, that this method will return false :

 public boolean calculate(float a, float b) { float c = a / b; return (a == (c * b)); } 
+5
source share
3 answers

The simple answer is yes. This example definitely returns false:

 public boolean alwaysFalse(){ float a=Float.MIN_VALUE; float b=Float.MAX_VALUE; float c = a / b; return a == c * b; } 

Update
More general answer: two cases where false occurs in your method:
1) when the value, if it is full (i.e., the division is evaluated to more digits than the value can be held)
2) after the indicator reaches a minimum, so you cannot divide further without losing the least significant bits of significance

You can build examples for " a " that guarantee a false value when the significant majority and the least significant bits are 1 (binary): 10000 ... 000001e10, etc.

+4
source

you can just check such cases yourself. For example, using this code:

 public class Main { public static void main(String[] args) { for (int i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; i++) { for (int j = Integer.MIN_VALUE; j < Integer.MAX_VALUE; j++) { if (!calculate(i, j)) System.out.println(i + " " + j); } } } public static boolean calculate(float a, float b) { float c = a / b; return (a == (c * b)); } } 

this returns many cases, for example:

1 - 6957633
1 - 6957635
1 - 6957644

+3
source

Yes.

 calculate(0,0) 

returns false because c will be NaN , so c * b will also be NaN , but a is 0, which is not NaN .

0
source

Source: https://habr.com/ru/post/1210008/


All Articles