Re: CTFE fmod ?

2015-11-20 Thread userABCabc123 via Digitalmars-d-learn

On Friday, 20 November 2015 at 13:44:11 UTC, rumbu wrote:
On Friday, 20 November 2015 at 11:16:13 UTC, userABCabc123 
wrote:

[...]



[...]


Not thoroughly tested and only works for doubles, but this must 
do the trick.


[...]


Thx, it works, easy to adapt to float.


Re: CTFE fmod ?

2015-11-20 Thread rumbu via Digitalmars-d-learn

On Friday, 20 November 2015 at 11:16:13 UTC, userABCabc123 wrote:
Does someone have a good CTFE fmod() function ? The problem is 
that std.math.fmod() is itself not available at CT, neither do 
floor() or similar functions necessary to get the quotient when 
the input value is two times over/under the bounds.






Any suggestion ? Or maybe this is a limit ?


Not thoroughly tested and only works for doubles, but this must 
do the trick.


double ctfe_trunc(double x) @trusted pure nothrow @nogc
{
ulong bits = *cast(ulong*)();
auto sign = bits & 0x8000;
long exponent = (bits >> 52) & 0x7FF;
auto mantissa = (bits & 0xF);

if (exponent == 0 && mantissa == 0)
return 0.0;
else if (exponent == 0x7FF && mantissa == 0)
return sign ? -double.infinity : double.infinity;
else if (exponent == 0x7FF)
return double.nan;

exponent -= 1023;
auto target = 52 - exponent;
if (target >= 0 && target <= 51)
{
auto msb = mantissa & (1UL << target);
auto lsb = mantissa & ~((1UL << target) - 1);
bits = sign | ((exponent + 1023)) << 52 | lsb;
mantissa += msb;
return *cast(double*)
}
else
return sign ? -0.0 : 0.0;
}

double ctfe_fmod(double x, double y) @safe pure nothrow @nogc
{
return x - ctfe_trunc(x / y) * y;
}