C# decreasing float slightly incorrect (0.4999999)
Hi,
I have a tiny problem with the logic here, I have an upgrade button that decreases fire rate of player by 0.05 but after couple of clicks, it will become (from 0.55) 0.4999999.
It should be (from 0.55) 0.5 not 0.4999999. I see that value in the hierarchy.
What's the problem here?
Thanks!
Answer by MaxGuernseyIII · Oct 21, 2017 at 01:54 PM
Floating point arithmetic is inherently imprecise.
Is it like a C# thing? I've never had such issue with other program$$anonymous$$g languages.
No, it's not a C# thing. It's a floating point thing
edit
If you want to play around with floating point numbers, here's an interactive IEEE 754 web based simulator which might help to understand floating point numbers better
@Bunny83 thanks for the reply and the video, I totally understand now, and it's not an issue as said in the video, 0.00001 doesn't really matter.
Think about it:
You're trying to model a number on the real number line with a fixed number of bits (32, in this case).
You can't model them all, right? You can only model about four billion of them.
There are arbitrary-precision data types, like a big integer and a big rational. They aren't supported out of the box with Unity, and they get slow fast. Double the precision, double the number of bits involved in a simple arithmetic operation.
If you need a quantized scale that you can make round-trips on, use an integer and then define a transformation from that integer into the scale. It still won't be perfect but at least you'll always have the same value for the same quantum.
@$$anonymous$$axGuernseyIII I already got it, but thanks for your comment.
Your answer
Follow this Question
Related Questions
C# float variable isnt behaving like its value 1 Answer
Problem with decrement 0 Answers
Float surprisingly turns to int or 0 1 Answer
float value is reset after every update 1 Answer
One script says the variable is 0 but the other says -37 1 Answer