Am Tue, 29 Sep 2015 21:04:00 +0000 schrieb Wulfrick <arm.p...@gmail.com>:
> Is there an interval arithmetic library in D? I couldn’t find one. > > In case I had to write my own, I understand that the IEEE > standard floating point arithmetic provides operations for > rounding up or down certain operations like summing, subtracting, > etc. (thus overriding the default behavior of rounding to nearest > representable). > > How do I access this functionality in D? At first I thought that > std.math.nextDown and nextUp is what I needed, but not so. > Apparently these functions return the previous or next > representable *after* the calculation has been done. > > For example, I would like the value of x+y rounded in the > arithmetic towards -\infty, which may or may not be nextDown(x+y). > > Any luck? > Thanks for reading! Yes, Phobos provides you with this thing: http://dlang.org/phobos/std_math.html#.FloatingPointControl Read the help carefully. End of the scope generally means "}". You can also use the C standard library from D and use: http://www.cplusplus.com/reference/cfenv/fesetround/ import core.stdc.fenv; fesetround( FE_DOWNWARD ); auto z = x + y; And if all that still isn't enough you can write it in inline assembler using the `fldcw` mnemonic. Note that the FP control word is per thread and any external code you call or even buggy interrupt handlers could change or reset it to defaults. Known cases include a faulty printer driver and Delphi's runtime, which enables FP exceptions to throw exceptions on division by 0. Just saying this so if it ever happens you have it in the back of your mind. Against interrupt handlers you probably cannot protect, but when calling other people's code it would be best not depend on what the FP control word is set to on return. `FloatingPointControl` is nice here, because you can temporarily set the rounding mode directly for a block of FP instructions where no external libraries are involved. -- Marco