|
|
|
|
Reply From: |
Lopy |
Godot can compare two Vector3s, but the default comparison might be too precise for your use case. You can try using bob.is_equal_approx(susan), or simply (bob-susan).length() < .1.
I will try this, my mind was exploding, as to why it wasn’t doing something so simple as a comparison, even printing both vectors shows they are the same, I would love to learn on why it was printing false.
Dragon20C | 2021-01-27 21:12
Thanks Lopy!, If you don’t mind me asking can you explain why the simple comparison doesnt works and also why using is_equal_approx() works does it check all possible versions of the vector or something, thanks again!
Dragon20C | 2021-01-28 07:53
Vectors use floating point numbers. Floats can’t be exactly compared like ints. This isn’t a Godot issue, it’s just how floats work on computers. There’s a standard floating point math adheres to on computers: IEEE754. So the solution when comparing floats is to check whether the difference between two values is smaller than some user-defined margin of error.
If you want a more detailed explanation, look at how computers represent numbers. They do this in binary. Numbers smaller than 1 are also represented in binary. Since computer memory for a single float is limited (Godot uses 4 bytes, or single precision floats, AFAIK), floating point precision is also limited. The same happens in decimal when you limit the precision of a calculation: When you add 0.05 and 0.04, you get 0.09, but if you limit yourself to one decimal after the point, you round this up to 0.1. When you do separate calculations starting off from the same numbers, and you have a sequence of operations, intermediate values will be limited to a specific precision defined by IEEE754, so you might end up with two results that are rounded to different values. So when you try to compare them, the comparison fails.
There’s another problem: Decimals and binary fractions can’t represent the same values exactly. For example, both systems can represent 0.5 exactly, but in decimal 0.1 can be represented exactly while in binary 0.1 can only be approximated (kinda like one third in decimal). So this leads to an additional error when you work with numbers you think should be exact , but can’t be represented exactly in binary.
Finally, floats internally use something like the scientific notation for numbers, only, again, not with base 10 but base 2. This is useful because it means that you can represent very big and very small numbers, but it also means that if you mix very small and very large numbers, you’ll get surprising behaviour due to the limited precision.
archeron | 2021-01-28 11:13