### float value equation

Hello. there seems to be a slight bug somewhere in my program (slight bug by .000001 to be precise)

I've been trying to think of a logical equation to solve this but i just cant wrap my head around it.

so this is the problem.

somewhere something is changing my float value by just a little so that it prints things like .599999 or .699999 and .799999 well you get it.
i need to check the numbers to make them correct somehow.

now one method i could use and would work would be like this (not sure if correct syntax, have not had to do this kind of if in quite a while)
 ``123456`` ``````if(x>.01 && x<.02){ x = .02; } else if (x>.02 && x<.03){ x = .03; }``````

ext.. ext...

but as a programmer I'm supposed to find logical ways to not have to repeatedly type so much. what other ways can i solve this problem?
Last edited on
floats cant accurately represent all numbers which means the computer will sometimes round the number to get the next closest number. leaving you with numbers like .599999999

this is a problem when dealing with money so some programmers will convert a float to two integers. One integer to represent the dollars part and one to represent the cents part.

another way is to check that the float is within a certain rage usually called epsilon this is similar to what you are doing. epsilon being a very small number if the float in question is less than float + epsilon and greater than float - epsilon then its considered ok.

I believe that libraries such as boost have classes that can accurately represent numbers and this is probably what most professional programmers would use.
Last edited on
One way you could solve this--maybe not the best--would be:

 ``12345`` ``````for(float i = 0; i < 1; i+= 0.01) //change the definition/inequality to suit values for x { if(x > i && x < i+0.01) x = i+0.01; }``````

A better solution might be possible, but I'd have to see the context--i.e. what modifies the float value.
its a double buffered key input in opengl. once its hit it outputs the x value (same issues with the Y) of the location of my tested object to the console. its only adding or subtracting .10 at a time . being why i didn't understand why it occurred. then the console is throwing me numbers that would confuse the average user of my program. if you really wanted to look into it i don't mind sharing details just don't know if thats something you actually would want to look into. its just a simple opengl app that displays an object with the options of movement/rotation.
Topic archived. No new replies allowed.