I read the unity scripting documentation, but I didn’t understand the difference between the two.
Here is the links of the documentation.
The difference is that Mathf.Floor returns a float, and Mathf.FloorToInt returns an integer. For example, this works:
float f = Mathf.Floor(1.5f);
This also works, because int can be implicitly converted to float:
float f = Mathf.FloorToInt(1.5f);
However, this doesn’t work, because the result is a float, which cannot be implicitly converted to int:
int i = Mathf.Floor(1.5f);
So you use Mathf.FloorToInt when the result needs to be an int.
Also,
Mathf.FloorToInt is just a convenience function that does
static public int FloorToInt(float value) {
return (int)Mathf.Floor(value);
}
Mainly useful for the reasons stated in the above post. It also reduces clutter because it offers a more readable alternative to type casting (and truncating due to real → integer downcasting) used in situ.
It is however, far better to use System.MathF library and introduce your own FloorToInt which works the same
static public int FloorToInt(float value) {
return (int)MathF.Floor(value);
}
It is better because Mathf.Floor actually does this
static public float Floor(float value) {
return (float)System.Math.Floor((double)value);
}
So FloorToInt ends up doing this (with an extra function call; it might be inlined if you’re lucky)
static public int FloorToInt(float value) {
return (int)(float)System.Math.Floor((double)value);
}
Well, the cast to float would not happen as it’s implemented like this. So it calls the System.Math.Floor method which operates on doubles and the double result would be casted directly to int which gives the best accuracy when it comes to floating point rounding.
Indeed, but my post would be longer and more complicated. Regardless, if you’re starting with a 32-bit float, you want speed and not accuracy. And I wrote “it might be inlined if you’re lucky” exactly because I’ve considered the double → int optimization, the compiler would flatten this construct entirely (edit: even if it had a function call I doubt it would be kept since it’s practically an expression-bodied static method in a static class; I believe that’s aggressively inlined by default). Still there is a needless 32-bit → 64-bit conversion involved.
Yes, that’s true. Though I’m not sure it has such a huge effect. The FPU usually works with extended precision internally which has 80 bits instead of 64 or 32. Yes some additional conversions potentially could be avoided, but it’s hard to tell for sure. Has anyone done some performance tests on this? Though different hardware could yield quite different results (x86, ARM, …).
In addition the C# specification specifically states that it could carry out floating point calculations in a higher precision anyways, but it’s up to the implementation I guess.