Turning floats into Vectors results in added decimals

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By joakim1999

When i run this code:

var vec = Vector2(200.714, 201.339)
print(str(vec))

The output says:

(200.714005, 201.339005)

Can someone explain why this happens?

:bust_in_silhouette: Reply From: SIsilicon

This isn’t really a problem with Godot but rather is a general issue when handling decimals in binary. You see, your computer can only handle floating point numbers with so much precision. A number like 200.714 would require infinite precision to represent exactly. See for yourself here. Since floating point numbers can only be represented with finite precision (obviously), the only thing you can do is round to the number that is closest to it that you can represent. So really you can’t do anything about that rounding error but to make sure that it doesn’t accumulate the error. To learn more about floating point arithmetic visit the Wikipedia.

Then why does it vary like this:

var preciseFloat = 200.71
print(preciseFloat)
var vector = Vector2(preciseFloat, preciseFloat)
print(vector)
print(vector.x)
print(vector.y)

Gives the output:

200.71
(200.710007, 200.710007)
200.710007
200.710007

Both the float that I made as a variable and the floats in the Vector2 are supposed to have the same precision. What is happening to the float when it is put in a data type that are supposed to be just two floats? Why does it lose precision?

joakim1999 | 2018-07-29 16:55