Adding 0.1f completely broken

Godot Version

4.3 C#

Question

When adding 0.1f to a variable

if (Input.IsActionJustPressed("scaleup")) // mouse wheel up/up arrow
	{
		ScaleModifier += 0.1f;
		GD.Print(""+ScaleModifier);
	}

as expected, it goes from 1 to 1.1, 1 to 1.2, and then suddenly, 1.2 to 1.3000001? and so on, going down messes it up even more, it adds random uneccesary decimals.

that’s how floats works if you want/needed use double for double precision

Don’t worry, C# is working as intended. Or better put, that’s floating-point arithmetic working as intended.

Why this happens is a long and complicated story that isn’t easily summarized. The short explanation (that is very wrong, but sufficiently accurate to cover the problem you’re facing) is that floats were invented as a way to represent real numbers using only a limited amount of your computer’s memory. A float in C# is four bytes which, using logarithms and mantissas, can be used to represent a wide range of real numbers, both small and large.

The problem with this approach is that there are vastly more real numbers than you can fit into four bytes. So, certain numbers cannot be represented with floats-- only their nearest neighbors can. That’s what you’re seeing here.

There’s a different data type in C# called a ‘double’. It effectively uses the same trick as your regular float, except it uses eight bytes. That enables it to represent way more numbers, but still not the full set of real numbers (which is an immensely large set.)

In practice, this lack of precision isn’t a big deal. Floats are more precise the nearer their value is to zero and more imprecise for very large numbers. Unless you’re keeping track of the distance between earth and sun as measured in centimeters, the error is pretty much always negligible.

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.