Please explain me this - trouble with float
I want to see if a*b=1, that is a=1/b
a and b are float if (a*b==1) never seems to work (for, let's say a=1.0/2.0 and b=2.0) Why is that? |
Don't know, it works for me using C programming...
My only thoughts are you forgot to include the math library or you forgot to define the variables as float or double... |
Quote:
|
Quote:
Code:
const float epsilon = 0.00001f; Code:
float c = a*b; http://www.math.grin.edu/~stone/cour...EEE-reals.html or one of other million web pages about the same issue. |
With floating point numbers, your result may be 1.9999999999999 or something similar. A floating point fraction (base 10) may not be exactly convertable to a base 2 floating point number.
Instead of an equality test for floating point numbers you should check if the difference is below a small delta value. For example, if you use a floating point variable to control a for loop and you test for equality to terminate the root, then the loop may not end. |
First off -
It's standard (ie., best practice) to use these comparison macros for floats and doubles (floating point numbers): Code:
isgreater(x,y) The suggestion of rolling your own epsilon, while okay, still has some problems - which is why these macros came about. A very long time ago. |
The use of these macros is advisable, are iso standard and maybe considered best practice but windows maths header does not include them; I normally code on windows (because theres just is not an ide which compares to visual studio in my opinion) and therefore use the above method rather than the macros. As I want my apps to work on both windows and nix.
|
Perhaps you can check if the macros are defined and if not roll your own macros.
|
Regarding float comparison in if loop
dmail is almost to the point.
The storage data format for float in memory consists of integer data and its precision information. Thats why it doesnt works as it seems to be in " if(condition)" , because this loops works well only for integer values or binary values. In case of float this loop compares the precision values and gives unexpected results, sometimes it works. better way for float comparision is to first separate the integer and data parts from the float byte. Regards geek |
thank you guys. I figured that out alone. the problem was that it never is exactly 1 when it comes to float.
thanks again. nice responces |
The same question also came up in this thread:
http://www.linuxquestions.org/questi...d.php?t=416939 |
Just do this:
Code:
#define FLOAT_EQUAL(X, Y) (X < (Y+epsilon) && X > (Y-epsilon)) Code:
float x, y; |
Quote:
There's vi ... |
All times are GMT -5. The time now is 05:49 AM. |