1

Can someone give a simplest example, when Mathf.Approximately gives true?

A try the following and it is always false:

Debug.Log(Mathf.Approximately(0.0001f, 0.0f));  // False
Debug.Log(Mathf.Approximately(0.00000001f, 0.0f));  // False
Debug.Log(Mathf.Approximately(0.00000000000001f, 0.0f));  // False
arael6
  • 19
  • 5

1 Answers1

2

The documentation says that they're equal if they are "within a very small value (epsilon)".

Epsilon is documented as "the smallest value a float can have different from zero".

How small is that? FloatMinNormal or FloatMinDenormal depending on IsFlushToZeroEnabled, which as you can see from source code would be about 1e-38, much smaller than 0.00000000000001f.

For non-zero values, the exact computation depends on the order of magnitude of the numbers, you can check out the source code for the precise formula.

Some numbers (e.g. 0.1) can't be represented exactly with a float. This is why Approximately can be more useful than straight equality. It is a complex topic, though, that needs more than a SO answer to fully develop. If you want to learn more, maybe start there: https://floating-point-gui.de/

jods
  • 4,581
  • 16
  • 20