Floating Point Imprecision

Hello. I was aware of the issue with floating point imprecision prior to this lesson, but I’m glad Sam covered it. However, we’ve used tests for a float == 0 before, without mention. Specifically, in the Health.cs file, we have…

        public void TakeDamage(GameObject instigator, float damage)
        {

            healthPoints.value = Mathf.Max(healthPoints.value - damage, 0);
            if (healthPoints.value == 0)
            {

                Die();
                AwardExperience(instigator);
            }
            else
            {
                takeDamage.Invoke(damage);
            }

        }

healthPoints is a LazyValue, but it was previously a normal float. Why is it safe to check the float healthPoints or healthPoints.value for equality with 0?

It may be because we will set it to 0. When we take damage, we subtract the damage from the health. eventually it will go below 0 and we will then set it to exactly 0

So if you set it to 0, you can safely test for equality with 0?

If you explicitly set it 0, you can test for zero, yes. If it’s the result of a floating point operation (for example: 10f -5f -1f-4f; you should not trustthe results. To be honest, best practice is to always use Mathf.Approximately. With some code editors, healthPoints.value==0 will be flagged with a warning about floating point comparison.

In my personal Health scripts, I always use ints for the values (meaning I have to convert BaseStats.GetStat(Stat.Health) to an int with Mathf.FloorToInt. I still prefer the stats and stat modifiers to be floats until they get into health, where they are converted.

2 Likes

Thanks Brian. Yeah, I prefer health to be integers also (can’t really think of an occasional where I would need decimals), but I also like to keep my code in sync with Sam’s while I’m taking the course. I’ll probably revisit once I finish off this course.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms