TL;DR:
Luau floating-point calculations are somewhat inaccurate. Why is that?
Recently, I was creating a system where a player could upgrade the cooldown of his tools and needed to get a percentage of how upgraded the tool was. However, when printing the output of the code, I noticed that there was a floating-point error. Here’s a simplified version of my code:
local startCooldown = 1.5
local endCooldown = 0.5
local currentCooldown = 1.3
local percent = (currentCooldown - startCooldown) / (endCooldown - startCooldown)
print(percent) -- Outputs 0.19999999999999996
The output is 0.19999999999999996
, when the expected value should be 0.2
This is the same code but in C++:
#include <iostream>
using namespace std;
int main()
{
float startCooldown = 1.5;
float endCooldown = 0.5;
float currentCooldown = 1.3;
// Equivalent of the print() function
cout << (currentCooldown - startCooldown) / (endCooldown - startCooldown); // Outputs 0.2
return 0;
}
Here, the output matches the expected value of 0.2
.
I did some more testing:
print(0.1 + 0.2) -- Outputs 0.30000000000000004
#include <iostream>
using namespace std;
int main()
{
cout<< 0.1 + 0.2; // Outputs 0.3
return 0;
}
I am aware that this happens because certain decimal values can’t be perfectly represented in binary. My theory is that there are certain techniques which aim to improve accuracy that are disabled in Luau.
Does anyone know why this happens? Why did Roblox choose to disable the accuracy improvements?