Not able to check Light2D's energy when its set to 0.7

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By user721

When Light2D energy set to 0.5
Light2D’s script:

extends Light2D

var se = 0

func _physics_process(delta):
	check()

func check():
	se = self.energy
	if se == 0.5:
		print(1)
	else:
		print(0)

Output:

1
1
1

BUT when energy set to 0.7

extends Light2D

var se = 0

func _physics_process(delta):
	check()

func check():
	se = self.energy
	if se == 0.7:
		print(1)
	else:
		print(0)

Output:

0
0
0

Values of 0.6, 0.7, 0.8, and 0.9 results in the same. The debugger shows no error as well. What am I missing?

:bust_in_silhouette: Reply From: AlexTheRegent

It might be floating point issue, because there are infinite number of values between any two float numbers. This is the reason why float values are stored with some precision. Try to check your values with some tolerance, i.e. instead of writing

if se == 0.7:

try

if (se - 0.7) < 0.001:

Godot has built-in is_equal_approx() and is_zero_approx() functions for this. You don’t need to use a manual epsilon value most of the time.

Calinou | 2021-08-25 06:39