[solved] Need help with ZScript floating point epsilon

Archive of the old editing forum
Forum rules
Before asking on how to use a ZDoom feature, read the ZDoom wiki first. This forum is archived - please use this set of forums to ask new questions.
User avatar
Nash
 
 
Posts: 17296
Joined: Mon Oct 27, 2003 12:07 am
Twitch ID: nashmuhandes
Github ID: nashmuhandes
Location: Kuala Lumpur, Malaysia

[solved] Need help with ZScript floating point epsilon

Post by Nash »

I almost have no idea what this is to be honest but I think I know what's going on with my problem. I have this:

Code: Select all

// just some arbitrary value, also note that It can be positive or negative
double f = FRandom(-555555.0, 555555.0);

void somefunction()
{
    f *= 0.9;
}
 
So this number will eventually be decreased with time. I want the multiplication to STOP when - put it in plain english - "the number is as good as 0".

How do I do this? I've tried the usual comparison operators but I can't get it to work... I guess due to rounding errors?
Last edited by Nash on Mon Jul 24, 2017 5:09 am, edited 1 time in total.
dpJudas
 
 
Posts: 2869
Joined: Sat May 28, 2016 1:01 pm

Re: Need help with ZScript floating point epsilon

Post by dpJudas »

Mathematically, what you are doing here would never reach a zero value, even if floats didn't have precision loss.

The solution is to define a cutoff value that is considered "as good as 0". You then check if the number is closer to zero than this value:

Code: Select all

f *= 0.9;
float virtuallyZero = 0.0000001;
if (abs(f) <= virtuallyZero) f = 0.0;
User avatar
Nash
 
 
Posts: 17296
Joined: Mon Oct 27, 2003 12:07 am
Twitch ID: nashmuhandes
Github ID: nashmuhandes
Location: Kuala Lumpur, Malaysia

Re: Need help with ZScript floating point epsilon

Post by Nash »

Thanks, that's precisely what I was looking for. :D

Return to “Editing (Archive)”