This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

It would be great, so that I can gain a better understanding, if someone could explain to me why Godot calculates as follows:

var a = 100 / (0 + 7) * 7
var b = 100 / (0 + 17) * 17
var c = 100 / (4 + 17) * 17
print(a)
print(b)
print(c)

(Incorrect) Results: a=98, b=85, c=68

var a = 100 / (float(0) + 7) * 7
var b = 100 / (float(0) + 17) * 17
var c = 100 / (float(4) + 17) * 17
print(a)
print(b)
print(c)

(Correct) Results: a=100, b=100, c=80.95238

Godot version v3.5.stable.official
in Engine by (12 points)

You may have seen warnings in the console about losing precision?

1 Answer

+2 votes

Probably because the variables are assumed to be int and not floats and narrowing conversion occurs. Its best to use types when you do not want that to happen.

var a : float = 100.0 / (0.0 + 7.0) * 7.0
var b : float = 100.0 / (0.0 + 17.0) * 17.0
var c : float = 100.0 / (4.0 + 17.0) * 17.0
print(a)
print(b)
print(c)
by (2,018 points)

This is not unique to gdscript. In many programming languages, math performed on only integers always results in an integer. Really, if you elevate any of the values in the expression to a float, the result will also be a float. So, for that first example, just this would give you the expected result:

var a = 100.0 / (0 + 7) * 7  # change 100 to a float value
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.