Godot Version
v4.5.1.stable.official [f62fdbde1] Linux
Question
Hi,
Almost finished with our next Godot video game.
We are having trouble with a particular math equation.
It should work, but fails?
Below is the source and a screenshot, hope you can help us!
func CheckEquationNewPerfect():
ConvertTilesToString()
print("fullEquation = ", ValueToCheck)
var splitEquation = ValueToCheck.split("=", true, 0)
var expression = Expression.new()
expression.parse(splitEquation[0])
var resultLeft = expression.execute()
print("resultLeft = ", resultLeft)
var expressionTwo = Expression.new()
expressionTwo.parse(splitEquation[1])
var resultRight = expressionTwo.execute()
print("resultRight = ", resultRight)
if (float(resultLeft) == float(resultRight)): # Fails here?
Floats should be compared via is_equal_approx(), not ==. Try if that fixes it.
2 Likes
To add on to @hyvernox’s answer: comparing two variables of type float for equality is a tricky thing to do. floats aren’t real numbers; they’re approximations that inherently have limited precision.
Under the hood, a float is four bytes and a bunch of math that can be used to represent some real numbers perfectly, but not all. Here is a good converter that shows the difference between what number you’re trying to represent and what the computer stores in memory (i.e. the error.)
This conversion error isn’t the same for every number. Numbers closer to zero have a smaller error than numbers farther away. (Try converting both 2.1 and 10000.1 to a float with the converter, and you’ll see the error is larger for the latter.) That’s why direct comparisons with floats tend to fail: you’re not subtracting the numbers you think you are subtracting.
Here’s a small program in C# that demonstrates this effect:
using System;
public class FloatExample
{
public static void Main(string[] args)
{
float a = 10000.1f; // Cannot be represented flawlessly. Closest number that can be: 10000.099609375
float b = 10000f; // A float can represent this number flawlessly (i.e. error is zero)
Console.WriteLine(a - b); // Prints: 0.09960938
float c = 0.1f;
Console.WriteLine(c == (a - b)); // Prints: False
}
}
1 Like