Fastest implementation of the frac function in C#
Posted
by user349937
on Stack Overflow
See other posts from Stack Overflow
or by user349937
Published on 2010-06-16T07:45:20Z
Indexed on
2010/06/16
7:52 UTC
Read the original article
Hit count: 255
I would like to implement a frac function in C# (just like the one in hsl here http://msdn.microsoft.com/en-us/library/bb509603%28VS.85%29.aspx) but since it is for a very processor intensive application i would like the best version possible. I was using something like
public float Frac(float value)
{
return value - (float)Math.Truncate(value);
}
but I'm having precision problems, for example for 2.6f it's returning in the unit test
Expected: 0.600000024f But was: 0.599999905f
I know that I can convert to decimal the value and then at the end convert to float to obtain the correct result something like this:
public float Frac(float value)
{
return (float)((decimal)value - Decimal.Truncate((decimal)value));
}
But I wonder if there is a better way without resorting to decimals...
© Stack Overflow or respective owner