-4

I am coding with the unity scripting API but I don't think that changes anything.

I have a variable playerMovementScript.rightWallX that is a float and is equal to -20.84.

I then have this line of code:

Debug.Log(-21.24f == playerMovementScript.rightWallX - 0.4f);

It always prints false. I feel like I'm missing something obvious cause I'd like to think I'm not THAT new to coding. Any help would be appreciated.

Elias
  • 11
  • 1

2 Answers2

1

Floating points not accurate. Use them only for fast calculations. If u want to compare 2 floats use if (Mathf.Approximately(floatA,floatB))

SntSdg
  • 36
  • 3
  • While your suggestion is spot on, the reasoning isn't quite right: floating point is very accurate. The problem is not accuracy, but the inability to represent most base-ten fraction numbers in base-two (binary) without infinite precision. This is because 0.1 in decimal is 0.001100110011... (repeats forever) in binary. However, 32-bit floats have only 24 significant bits (23 plus an implicit leading 1 bit), so 0.1d is represented as 1.10011001100110011001101*2^-3, with that final 1101 due to rounding. Thus multiplying by 10(decimal) results in a number slightly larger than 1.0. – taniwha Aug 28 '22 at 00:01
  • (continuation of above) However, one in 16-million (24 bits) is pretty accurate and even fairly precise. The problem is there are tricks for dealing with the rounding, including, as you suggest, not doing *direct* comparisons between floats, and thus goes against our intuition. – taniwha Aug 28 '22 at 00:04
0

The reason it prints false is because you are using the == operator, which checks if 2 things are equal, therefore since you are doing -21.24f == playerMovementScript.rightWallX - 0.4f, the result is unequal and then it prints false. I am pretty sure you meant =, but we all make mistakes.

Abyssal
  • 1
  • 3