x


Bad result on a rest between 2 floats

I have 2 floats variables: lets say "money" and "bet". At some point, I do money = money - bet; or money -= bet;

bet is from 0.05 to 1 and money starts at 10000. Lets take 0.05 for bet. The first rest, money equals 9999.95. The second rest, is 9999.91. And then alternates resting 0.05 or 0.04.

Why is this happening? Any idea?

more ▼

asked Jan 04 '12 at 10:58 PM

DarkSlash gravatar image

DarkSlash
41 12 14 16

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

The float precision is about 7 digits, thus you should not have problems with 10000 and 0.05 - but with 100000 and 0.05 this error would appear, for sure.
If you must work with such wide range of values, declare the variables as double:

var money: double = 1000000;
var bet: double = 0.05;

Double precision is about 16 digits, thus the player can even break the bank without loosing precision.

more ▼

answered Jan 04 '12 at 11:53 PM

aldonaletto gravatar image

aldonaletto
42.5k 16 43 202

Flawless answer! That was the problem! Thanks! :)

Jan 05 '12 at 06:01 PM DarkSlash
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x224
x185
x9

asked: Jan 04 '12 at 10:58 PM

Seen: 449 times

Last Updated: Jan 05 '12 at 07:15 PM