Hi,

I'm doing a bouncing ball game. i'm using y=mx + b

I want to know when y hits certain numbers. that means it had a collision. the numbers are whole numbers like 539 etc. I increment Y slowly because i also want to not let x move much. when i do

y+=.25; things are ok. y is a double.

if i do y+=.1; i have problems

I looked at the output, and instead of Y being equal to say 539, it's

538.9999999999998176 or something.

whats going on? how to get rid of this fuzyness particularly in cases where i know i'm just adding .1.

Mike

If you're only adding .1 or .25 etc, but the result shows up as something which isn't a multiple of .1 or .25, then y was clearly not equal to a multiple of .1 or .25 to begin with. In other words your initial y value must have been something weird; how was y initially set?

whats going on?

Read about floating point accuracy.

how to get rid of this fuzyness particularly in cases where i know i'm just adding .1.

You might try sticking with integers and using fixed-point math... with the example you posted, you could use a scaling factor of 100: y would actually equal 53900, add 10 instead of 0.1, add 25 instead of 0.25. You'd just have to remember to divide by 100 when printing values.

If you're only adding .1 or .25 etc, but the result shows up as something which isn't a multiple of .1 or .25, then y was clearly not equal to a multiple of .1 or .25 to begin with. In other words your initial y value must have been something weird; how was y initially set?

More likely it's due to floating point representation, in particular: The decimal value 0.1 has an infinite binary expansion, so it's impossible to represent accurately in a floating-point number.

Interesting. Guess that's it then.

now that i know the issue i got some ideas for work arounds. In areas i know i can have fuzy math i'm going to have to find better methods when i want essentially integer calculations. I dont think i'll make the whole thing integer though. thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.