Vector2/Vector3 deviation after initialization

Godot Version

Godot Engine v4.6.2.stable.official [71f334935]

Question

I noticed something strange while programming with Vector2 and Vector3:

# Example:
var vec: Vector2 = Vector2(5.25, 4.69)
print(vec) # Output: (5.25, 4.69)

# However:
print(vec.x) # Output: 5.25
print(vec.y) # Output: 4.69000005722046

This caused some bugs in my game. Especially when I compare the x-values of two vectors and the condition is sometimes true and sometimes false. Depending on weather the x-value is actually 4.69 (like I initialized it in the expample) or in reality 4.69000005722046.

I don’t know if this is a quirk of floats, my inexperience, or a bug. I just wanted to know if there’s a simple solution or workaround for it? Or if someone noticed it before?

With kind regards,
DieMacht

This is simple floating point representation limitations, 4.69 is not representable exactly as a float, the difference in printing the vector and each component is for formatting

Also note that vector components are single precision floats (32 bits), while the plain float type uses double precision (64 bits).

For the comparisons, use is_equal_approx(a.x, b.x) (or a.is_equal_approx(b) for the whole vector) instead of ==. And if those are grid positions, Vector2i is worth it, whole numbers compare exactly so this can’t happen