# This is precise math???

Discussion in 'C' started by danielakkerman, Jan 3, 2007.

1. ### danielakkermanNew Member

Joined:
Dec 25, 2006
Messages:
9
0
Trophy Points:
0
Hi,
I am sorry if I am being too annoying with my questions, but here's a really puzzling one, especially, since I'd been running the same operation in Java, and it worked PERFECTLY!
here's the code:
Code:
```double i = 0;
while(i<5){
if(i*2 == 1.6)printf("%s", "Yay");
i=i+0.1;
}
```
The point is, it dosen't find the answer(which is btw: 0.8, i should be equal to 0.8).
I've tried, float, coverting double to float, and backwards...
Thanks,
Thanks again,
Daniel

2. ### ever_thusNew Member

Joined:
Jan 3, 2007
Messages:
53
0
Trophy Points:
0
using comparisons is tricky with floating points, which is what a double type is. As an analogy consider decimal numbers. The standard way to to represeent 1/3 is 0.33333333333 (for as long as you want). But multiply this by 3 and you don't have 1. The same problems occur with the binary numbers computers use. Different compilers have different ways of representing floating points, which might be why the program worked in Java.

3. ### DaWeiNew Member

Joined:
Dec 6, 2006
Messages:
835
5
Trophy Points:
0
Occupation:
Semi-retired EE
Location:
Texan now in Central NY
http://www.daweidesigns.com
Ever_thus gives a great example. You might also consider this: if a 32-bit float has more range than a 32-bit integer, where's the magic? There isn't any. Range is gained by a loss of precision and accuracy. If I give you only 3 decimal places, but an exponent to go with it, you can express a ton of numbers, but you can't express them all. One deals with this by measuring a result in terms of an error range, rather than by looking for an exact equality.

4. ### danielakkermanNew Member

Joined:
Dec 25, 2006
Messages:
9
0
Trophy Points:
0
Actually,
Whenever I ask the program to print out the multiplication of i*2
One of the answers that comes is 1.6(the correct one!).
Thus, I was only able to reckon that something must wrong with the if statement rather then the precision.
1.6 is a definite fraction. Not infinite like 1/3.
Also, As I've mentioned earlier, the multiplication 'goes-on' just fine.
Any other suggestions?
Thanks,
Daniel

5. ### DaWeiNew Member

Joined:
Dec 6, 2006
Messages:
835
5
Trophy Points:
0
Occupation:
Semi-retired EE
Location:
Texan now in Central NY