forked from dlang/phobos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumeric.d
3473 lines (3139 loc) · 106 KB
/
numeric.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Written in the D programming language.
/**
This module is a port of a growing fragment of the $(D_PARAM numeric)
header in Alexander Stepanov's $(LINK2 https://en.wikipedia.org/wiki/Standard_Template_Library,
Standard Template Library), with a few additions.
Macros:
Copyright: Copyright Andrei Alexandrescu 2008 - 2009.
License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP erdani.org, Andrei Alexandrescu),
Don Clugston, Robert Jacques, Ilya Yaroshenko
Source: $(PHOBOSSRC std/numeric.d)
*/
/*
Copyright Andrei Alexandrescu 2008 - 2009.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
module std.numeric;
import std.complex;
import std.math;
import std.range.primitives;
import std.traits;
import std.typecons;
/// Format flags for CustomFloat.
public enum CustomFloatFlags
{
/// Adds a sign bit to allow for signed numbers.
signed = 1,
/**
* Store values in normalized form by default. The actual precision of the
* significand is extended by 1 bit by assuming an implicit leading bit of 1
* instead of 0. i.e. `1.nnnn` instead of `0.nnnn`.
* True for all $(LINK2 https://en.wikipedia.org/wiki/IEEE_floating_point, IEE754) types
*/
storeNormalized = 2,
/**
* Stores the significand in $(LINK2 https://en.wikipedia.org/wiki/IEEE_754-1985#Denormalized_numbers,
* IEEE754 denormalized) form when the exponent is 0. Required to express the value 0.
*/
allowDenorm = 4,
/**
* Allows the storage of $(LINK2 https://en.wikipedia.org/wiki/IEEE_754-1985#Positive_and_negative_infinity,
* IEEE754 _infinity) values.
*/
infinity = 8,
/// Allows the storage of $(LINK2 https://en.wikipedia.org/wiki/NaN, IEEE754 Not a Number) values.
nan = 16,
/**
* If set, select an exponent bias such that max_exp = 1.
* i.e. so that the maximum value is >= 1.0 and < 2.0.
* Ignored if the exponent bias is manually specified.
*/
probability = 32,
/// If set, unsigned custom floats are assumed to be negative.
negativeUnsigned = 64,
/**If set, 0 is the only allowed $(LINK2 https://en.wikipedia.org/wiki/IEEE_754-1985#Denormalized_numbers,
* IEEE754 denormalized) number.
* Requires allowDenorm and storeNormalized.
*/
allowDenormZeroOnly = 128 | allowDenorm | storeNormalized,
/// Include _all of the $(LINK2 https://en.wikipedia.org/wiki/IEEE_floating_point, IEEE754) options.
ieee = signed | storeNormalized | allowDenorm | infinity | nan ,
/// Include none of the above options.
none = 0
}
private template CustomFloatParams(uint bits)
{
enum CustomFloatFlags flags = CustomFloatFlags.ieee
^ ((bits == 80) ? CustomFloatFlags.storeNormalized : CustomFloatFlags.none);
static if (bits == 8) alias CustomFloatParams = CustomFloatParams!( 4, 3, flags);
static if (bits == 16) alias CustomFloatParams = CustomFloatParams!(10, 5, flags);
static if (bits == 32) alias CustomFloatParams = CustomFloatParams!(23, 8, flags);
static if (bits == 64) alias CustomFloatParams = CustomFloatParams!(52, 11, flags);
static if (bits == 80) alias CustomFloatParams = CustomFloatParams!(64, 15, flags);
}
private template CustomFloatParams(uint precision, uint exponentWidth, CustomFloatFlags flags)
{
import std.meta : AliasSeq;
alias CustomFloatParams =
AliasSeq!(
precision,
exponentWidth,
flags,
(1 << (exponentWidth - ((flags & flags.probability) == 0)))
- ((flags & (flags.nan | flags.infinity)) != 0) - ((flags & flags.probability) != 0)
); // ((flags & CustomFloatFlags.probability) == 0)
}
/**
* Allows user code to define custom floating-point formats. These formats are
* for storage only; all operations on them are performed by first implicitly
* extracting them to `real` first. After the operation is completed the
* result can be stored in a custom floating-point value via assignment.
*/
template CustomFloat(uint bits)
if (bits == 8 || bits == 16 || bits == 32 || bits == 64 || bits == 80)
{
alias CustomFloat = CustomFloat!(CustomFloatParams!(bits));
}
/// ditto
template CustomFloat(uint precision, uint exponentWidth, CustomFloatFlags flags = CustomFloatFlags.ieee)
if (((flags & flags.signed) + precision + exponentWidth) % 8 == 0 && precision + exponentWidth > 0)
{
alias CustomFloat = CustomFloat!(CustomFloatParams!(precision, exponentWidth, flags));
}
///
@safe unittest
{
import std.math : sin, cos;
// Define a 16-bit floating point values
CustomFloat!16 x; // Using the number of bits
CustomFloat!(10, 5) y; // Using the precision and exponent width
CustomFloat!(10, 5,CustomFloatFlags.ieee) z; // Using the precision, exponent width and format flags
CustomFloat!(10, 5,CustomFloatFlags.ieee, 15) w; // Using the precision, exponent width, format flags and exponent offset bias
// Use the 16-bit floats mostly like normal numbers
w = x*y - 1;
// Functions calls require conversion
z = sin(+x) + cos(+y); // Use unary plus to concisely convert to a real
z = sin(x.get!float) + cos(y.get!float); // Or use get!T
z = sin(cast(float) x) + cos(cast(float) y); // Or use cast(T) to explicitly convert
// Define a 8-bit custom float for storing probabilities
alias Probability = CustomFloat!(4, 4, CustomFloatFlags.ieee^CustomFloatFlags.probability^CustomFloatFlags.signed );
auto p = Probability(0.5);
}
/// ditto
struct CustomFloat(uint precision, // fraction bits (23 for float)
uint exponentWidth, // exponent bits (8 for float) Exponent width
CustomFloatFlags flags,
uint bias)
if (((flags & flags.signed) + precision + exponentWidth) % 8 == 0 &&
precision + exponentWidth > 0)
{
import std.bitmanip : bitfields;
import std.meta : staticIndexOf;
private:
// get the correct unsigned bitfield type to support > 32 bits
template uType(uint bits)
{
static if (bits <= size_t.sizeof*8) alias uType = size_t;
else alias uType = ulong ;
}
// get the correct signed bitfield type to support > 32 bits
template sType(uint bits)
{
static if (bits <= ptrdiff_t.sizeof*8-1) alias sType = ptrdiff_t;
else alias sType = long;
}
alias T_sig = uType!precision;
alias T_exp = uType!exponentWidth;
alias T_signed_exp = sType!exponentWidth;
alias Flags = CustomFloatFlags;
// Facilitate converting numeric types to custom float
union ToBinary(F)
if (is(typeof(CustomFloatParams!(F.sizeof*8))) || is(F == real))
{
F set;
// If on Linux or Mac, where 80-bit reals are padded, ignore the
// padding.
import std.algorithm.comparison : min;
CustomFloat!(CustomFloatParams!(min(F.sizeof*8, 80))) get;
// Convert F to the correct binary type.
static typeof(get) opCall(F value)
{
ToBinary r;
r.set = value;
return r.get;
}
alias get this;
}
// Perform IEEE rounding with round to nearest detection
void roundedShift(T,U)(ref T sig, U shift)
{
if (sig << (T.sizeof*8 - shift) == cast(T) 1uL << (T.sizeof*8 - 1))
{
// round to even
sig >>= shift;
sig += sig & 1;
}
else
{
sig >>= shift - 1;
sig += sig & 1;
// Perform standard rounding
sig >>= 1;
}
}
// Convert the current value to signed exponent, normalized form
void toNormalized(T,U)(ref T sig, ref U exp)
{
sig = significand;
auto shift = (T.sizeof*8) - precision;
exp = exponent;
static if (flags&(Flags.infinity|Flags.nan))
{
// Handle inf or nan
if (exp == exponent_max)
{
exp = exp.max;
sig <<= shift;
static if (flags&Flags.storeNormalized)
{
// Save inf/nan in denormalized format
sig >>= 1;
sig += cast(T) 1uL << (T.sizeof*8 - 1);
}
return;
}
}
if ((~flags&Flags.storeNormalized) ||
// Convert denormalized form to normalized form
((flags&Flags.allowDenorm) && exp == 0))
{
if (sig > 0)
{
import core.bitop : bsr;
auto shift2 = precision - bsr(sig);
exp -= shift2-1;
shift += shift2;
}
else // value = 0.0
{
exp = exp.min;
return;
}
}
sig <<= shift;
exp -= bias;
}
// Set the current value from signed exponent, normalized form
void fromNormalized(T,U)(ref T sig, ref U exp)
{
auto shift = (T.sizeof*8) - precision;
if (exp == exp.max)
{
// infinity or nan
exp = exponent_max;
static if (flags & Flags.storeNormalized)
sig <<= 1;
// convert back to normalized form
static if (~flags & Flags.infinity)
// No infinity support?
assert(sig != 0, "Infinity floating point value assigned to a "
~ typeof(this).stringof ~ " (no infinity support).");
static if (~flags & Flags.nan) // No NaN support?
assert(sig == 0, "NaN floating point value assigned to a " ~
typeof(this).stringof ~ " (no nan support).");
sig >>= shift;
return;
}
if (exp == exp.min) // 0.0
{
exp = 0;
sig = 0;
return;
}
exp += bias;
if (exp <= 0)
{
static if ((flags&Flags.allowDenorm) ||
// Convert from normalized form to denormalized
(~flags&Flags.storeNormalized))
{
shift += -exp;
roundedShift(sig,1);
sig += cast(T) 1uL << (T.sizeof*8 - 1);
// Add the leading 1
exp = 0;
}
else
assert((flags&Flags.storeNormalized) && exp == 0,
"Underflow occured assigning to a " ~
typeof(this).stringof ~ " (no denormal support).");
}
else
{
static if (~flags&Flags.storeNormalized)
{
// Convert from normalized form to denormalized
roundedShift(sig,1);
sig += cast(T) 1uL << (T.sizeof*8 - 1);
// Add the leading 1
}
}
if (shift > 0)
roundedShift(sig,shift);
if (sig > significand_max)
{
// handle significand overflow (should only be 1 bit)
static if (~flags&Flags.storeNormalized)
{
sig >>= 1;
}
else
sig &= significand_max;
exp++;
}
static if ((flags&Flags.allowDenormZeroOnly)==Flags.allowDenormZeroOnly)
{
// disallow non-zero denormals
if (exp == 0)
{
sig <<= 1;
if (sig > significand_max && (sig&significand_max) > 0)
// Check and round to even
exp++;
sig = 0;
}
}
if (exp >= exponent_max)
{
static if (flags&(Flags.infinity|Flags.nan))
{
sig = 0;
exp = exponent_max;
static if (~flags&(Flags.infinity))
assert(0, "Overflow occured assigning to a " ~
typeof(this).stringof ~ " (no infinity support).");
}
else
assert(exp == exponent_max, "Overflow occured assigning to a "
~ typeof(this).stringof ~ " (no infinity support).");
}
}
public:
static if (precision == 64) // CustomFloat!80 support hack
{
ulong significand;
enum ulong significand_max = ulong.max;
mixin(bitfields!(
T_exp , "exponent", exponentWidth,
bool , "sign" , flags & flags.signed ));
}
else
{
mixin(bitfields!(
T_sig, "significand", precision,
T_exp, "exponent" , exponentWidth,
bool , "sign" , flags & flags.signed ));
}
/// Returns: infinity value
static if (flags & Flags.infinity)
static @property CustomFloat infinity()
{
CustomFloat value;
static if (flags & Flags.signed)
value.sign = 0;
value.significand = 0;
value.exponent = exponent_max;
return value;
}
/// Returns: NaN value
static if (flags & Flags.nan)
static @property CustomFloat nan()
{
CustomFloat value;
static if (flags & Flags.signed)
value.sign = 0;
value.significand = cast(typeof(significand_max)) 1L << (precision-1);
value.exponent = exponent_max;
return value;
}
/// Returns: number of decimal digits of precision
static @property size_t dig()
{
auto shiftcnt = precision - ((flags&Flags.storeNormalized) != 0);
immutable x = (shiftcnt == 64) ? 0 : 1uL << shiftcnt;
return cast(size_t) log10(x);
}
/// Returns: smallest increment to the value 1
static @property CustomFloat epsilon()
{
CustomFloat value;
static if (flags & Flags.signed)
value.sign = 0;
T_signed_exp exp = -precision;
T_sig sig = 0;
value.fromNormalized(sig,exp);
if (exp == 0 && sig == 0) // underflowed to zero
{
static if ((flags&Flags.allowDenorm) ||
(~flags&Flags.storeNormalized))
sig = 1;
else
sig = cast(T) 1uL << (precision - 1);
}
value.exponent = cast(value.T_exp) exp;
value.significand = cast(value.T_sig) sig;
return value;
}
/// the number of bits in mantissa
enum mant_dig = precision + ((flags&Flags.storeNormalized) != 0);
/// Returns: maximum int value such that 10<sup>max_10_exp</sup> is representable
static @property int max_10_exp(){ return cast(int) log10( +max ); }
/// maximum int value such that 2<sup>max_exp-1</sup> is representable
enum max_exp = exponent_max-bias+((~flags&(Flags.infinity|flags.nan))!=0);
/// Returns: minimum int value such that 10<sup>min_10_exp</sup> is representable
static @property int min_10_exp(){ return cast(int) log10( +min_normal ); }
/// minimum int value such that 2<sup>min_exp-1</sup> is representable as a normalized value
enum min_exp = cast(T_signed_exp)-bias +1+ ((flags&Flags.allowDenorm)!=0);
/// Returns: largest representable value that's not infinity
static @property CustomFloat max()
{
CustomFloat value;
static if (flags & Flags.signed)
value.sign = 0;
value.exponent = exponent_max - ((flags&(flags.infinity|flags.nan)) != 0);
value.significand = significand_max;
return value;
}
/// Returns: smallest representable normalized value that's not 0
static @property CustomFloat min_normal() {
CustomFloat value;
static if (flags & Flags.signed)
value.sign = 0;
value.exponent = 1;
static if (flags&Flags.storeNormalized)
value.significand = 0;
else
value.significand = cast(T_sig) 1uL << (precision - 1);
return value;
}
/// Returns: real part
@property CustomFloat re() { return this; }
/// Returns: imaginary part
static @property CustomFloat im() { return CustomFloat(0.0f); }
/// Initialize from any `real` compatible type.
this(F)(F input) if (__traits(compiles, cast(real) input ))
{
this = input;
}
/// Self assignment
void opAssign(F:CustomFloat)(F input)
{
static if (flags & Flags.signed)
sign = input.sign;
exponent = input.exponent;
significand = input.significand;
}
/// Assigns from any `real` compatible type.
void opAssign(F)(F input)
if (__traits(compiles, cast(real) input))
{
import std.conv : text;
static if (staticIndexOf!(Unqual!F, float, double, real) >= 0)
auto value = ToBinary!(Unqual!F)(input);
else
auto value = ToBinary!(real )(input);
// Assign the sign bit
static if (~flags & Flags.signed)
assert((!value.sign) ^ ((flags&flags.negativeUnsigned) > 0),
"Incorrectly signed floating point value assigned to a " ~
typeof(this).stringof ~ " (no sign support).");
else
sign = value.sign;
CommonType!(T_signed_exp ,value.T_signed_exp) exp = value.exponent;
CommonType!(T_sig, value.T_sig ) sig = value.significand;
value.toNormalized(sig,exp);
fromNormalized(sig,exp);
assert(exp <= exponent_max, text(typeof(this).stringof ~
" exponent too large: " ,exp," > ",exponent_max, "\t",input,"\t",sig));
assert(sig <= significand_max, text(typeof(this).stringof ~
" significand too large: ",sig," > ",significand_max,
"\t",input,"\t",exp," ",exponent_max));
exponent = cast(T_exp) exp;
significand = cast(T_sig) sig;
}
/// Fetches the stored value either as a `float`, `double` or `real`.
@property F get(F)()
if (staticIndexOf!(Unqual!F, float, double, real) >= 0)
{
import std.conv : text;
ToBinary!F result;
static if (flags&Flags.signed)
result.sign = sign;
else
result.sign = (flags&flags.negativeUnsigned) > 0;
CommonType!(T_signed_exp ,result.get.T_signed_exp ) exp = exponent; // Assign the exponent and fraction
CommonType!(T_sig, result.get.T_sig ) sig = significand;
toNormalized(sig,exp);
result.fromNormalized(sig,exp);
assert(exp <= result.exponent_max, text("get exponent too large: " ,exp," > ",result.exponent_max) );
assert(sig <= result.significand_max, text("get significand too large: ",sig," > ",result.significand_max) );
result.exponent = cast(result.get.T_exp) exp;
result.significand = cast(result.get.T_sig) sig;
return result.set;
}
///ditto
T opCast(T)() if (__traits(compiles, get!T )) { return get!T; }
/// Convert the CustomFloat to a real and perform the relavent operator on the result
real opUnary(string op)()
if (__traits(compiles, mixin(op~`(get!real)`)) || op=="++" || op=="--")
{
static if (op=="++" || op=="--")
{
auto result = get!real;
this = mixin(op~`result`);
return result;
}
else
return mixin(op~`get!real`);
}
/// ditto
real opBinary(string op,T)(T b)
if (__traits(compiles, mixin(`get!real`~op~`b`)))
{
return mixin(`get!real`~op~`b`);
}
/// ditto
real opBinaryRight(string op,T)(T a)
if ( __traits(compiles, mixin(`a`~op~`get!real`)) &&
!__traits(compiles, mixin(`get!real`~op~`b`)))
{
return mixin(`a`~op~`get!real`);
}
/// ditto
int opCmp(T)(auto ref T b)
if (__traits(compiles, cast(real) b))
{
auto x = get!real;
auto y = cast(real) b;
return (x >= y)-(x <= y);
}
/// ditto
void opOpAssign(string op, T)(auto ref T b)
if (__traits(compiles, mixin(`get!real`~op~`cast(real) b`)))
{
return mixin(`this = this `~op~` cast(real) b`);
}
/// ditto
template toString()
{
import std.format : FormatSpec, formatValue;
// Needs to be a template because of DMD @@BUG@@ 13737.
void toString()(scope void delegate(const(char)[]) sink, FormatSpec!char fmt)
{
sink.formatValue(get!real, fmt);
}
}
}
@safe unittest
{
import std.meta;
alias FPTypes =
AliasSeq!(
CustomFloat!(5, 10),
CustomFloat!(5, 11, CustomFloatFlags.ieee ^ CustomFloatFlags.signed),
CustomFloat!(1, 15, CustomFloatFlags.ieee ^ CustomFloatFlags.signed),
CustomFloat!(4, 3, CustomFloatFlags.ieee | CustomFloatFlags.probability ^ CustomFloatFlags.signed)
);
foreach (F; FPTypes)
{
auto x = F(0.125);
assert(x.get!float == 0.125F);
assert(x.get!double == 0.125);
x -= 0.0625;
assert(x.get!float == 0.0625F);
assert(x.get!double == 0.0625);
x *= 2;
assert(x.get!float == 0.125F);
assert(x.get!double == 0.125);
x /= 4;
assert(x.get!float == 0.03125);
assert(x.get!double == 0.03125);
x = 0.5;
x ^^= 4;
assert(x.get!float == 1 / 16.0F);
assert(x.get!double == 1 / 16.0);
}
}
@system unittest
{
// @system due to to!string(CustomFloat)
import std.conv;
CustomFloat!(5, 10) y = CustomFloat!(5, 10)(0.125);
assert(y.to!string == "0.125");
}
/**
Defines the fastest type to use when storing temporaries of a
calculation intended to ultimately yield a result of type `F`
(where `F` must be one of `float`, `double`, or $(D
real)). When doing a multi-step computation, you may want to store
intermediate results as `FPTemporary!F`.
The necessity of `FPTemporary` stems from the optimized
floating-point operations and registers present in virtually all
processors. When adding numbers in the example above, the addition may
in fact be done in `real` precision internally. In that case,
storing the intermediate `result` in $(D double format) is not only
less precise, it is also (surprisingly) slower, because a conversion
from `real` to `double` is performed every pass through the
loop. This being a lose-lose situation, `FPTemporary!F` has been
defined as the $(I fastest) type to use for calculations at precision
`F`. There is no need to define a type for the $(I most accurate)
calculations, as that is always `real`.
Finally, there is no guarantee that using `FPTemporary!F` will
always be fastest, as the speed of floating-point calculations depends
on very many factors.
*/
template FPTemporary(F)
if (isFloatingPoint!F)
{
version(X86)
alias FPTemporary = real;
else
alias FPTemporary = Unqual!F;
}
///
@safe unittest
{
import std.math : approxEqual;
// Average numbers in an array
double avg(in double[] a)
{
if (a.length == 0) return 0;
FPTemporary!double result = 0;
foreach (e; a) result += e;
return result / a.length;
}
auto a = [1.0, 2.0, 3.0];
assert(approxEqual(avg(a), 2));
}
/**
Implements the $(HTTP tinyurl.com/2zb9yr, secant method) for finding a
root of the function `fun` starting from points $(D [xn_1, x_n])
(ideally close to the root). `Num` may be `float`, `double`,
or `real`.
*/
template secantMethod(alias fun)
{
import std.functional : unaryFun;
Num secantMethod(Num)(Num xn_1, Num xn)
{
auto fxn = unaryFun!(fun)(xn_1), d = xn_1 - xn;
typeof(fxn) fxn_1;
xn = xn_1;
while (!approxEqual(d, 0) && isFinite(d))
{
xn_1 = xn;
xn -= d;
fxn_1 = fxn;
fxn = unaryFun!(fun)(xn);
d *= -fxn / (fxn - fxn_1);
}
return xn;
}
}
///
@safe unittest
{
import std.math : approxEqual, cos;
float f(float x)
{
return cos(x) - x*x*x;
}
auto x = secantMethod!(f)(0f, 1f);
assert(approxEqual(x, 0.865474));
}
@system unittest
{
// @system because of __gshared stderr
import std.stdio;
scope(failure) stderr.writeln("Failure testing secantMethod");
float f(float x)
{
return cos(x) - x*x*x;
}
immutable x = secantMethod!(f)(0f, 1f);
assert(approxEqual(x, 0.865474));
auto d = &f;
immutable y = secantMethod!(d)(0f, 1f);
assert(approxEqual(y, 0.865474));
}
/**
* Return true if a and b have opposite sign.
*/
private bool oppositeSigns(T1, T2)(T1 a, T2 b)
{
return signbit(a) != signbit(b);
}
public:
/** Find a real root of a real function f(x) via bracketing.
*
* Given a function `f` and a range `[a .. b]` such that `f(a)`
* and `f(b)` have opposite signs or at least one of them equals ±0,
* returns the value of `x` in
* the range which is closest to a root of `f(x)`. If `f(x)`
* has more than one root in the range, one will be chosen
* arbitrarily. If `f(x)` returns NaN, NaN will be returned;
* otherwise, this algorithm is guaranteed to succeed.
*
* Uses an algorithm based on TOMS748, which uses inverse cubic
* interpolation whenever possible, otherwise reverting to parabolic
* or secant interpolation. Compared to TOMS748, this implementation
* improves worst-case performance by a factor of more than 100, and
* typical performance by a factor of 2. For 80-bit reals, most
* problems require 8 to 15 calls to `f(x)` to achieve full machine
* precision. The worst-case performance (pathological cases) is
* approximately twice the number of bits.
*
* References: "On Enclosing Simple Roots of Nonlinear Equations",
* G. Alefeld, F.A. Potra, Yixun Shi, Mathematics of Computation 61,
* pp733-744 (1993). Fortran code available from $(HTTP
* www.netlib.org,www.netlib.org) as algorithm TOMS478.
*
*/
T findRoot(T, DF, DT)(scope DF f, in T a, in T b,
scope DT tolerance) //= (T a, T b) => false)
if (
isFloatingPoint!T &&
is(typeof(tolerance(T.init, T.init)) : bool) &&
is(typeof(f(T.init)) == R, R) && isFloatingPoint!R
)
{
immutable fa = f(a);
if (fa == 0)
return a;
immutable fb = f(b);
if (fb == 0)
return b;
immutable r = findRoot(f, a, b, fa, fb, tolerance);
// Return the first value if it is smaller or NaN
return !(fabs(r[2]) > fabs(r[3])) ? r[0] : r[1];
}
///ditto
T findRoot(T, DF)(scope DF f, in T a, in T b)
{
return findRoot(f, a, b, (T a, T b) => false);
}
/** Find root of a real function f(x) by bracketing, allowing the
* termination condition to be specified.
*
* Params:
*
* f = Function to be analyzed
*
* ax = Left bound of initial range of `f` known to contain the
* root.
*
* bx = Right bound of initial range of `f` known to contain the
* root.
*
* fax = Value of `f(ax)`.
*
* fbx = Value of `f(bx)`. `fax` and `fbx` should have opposite signs.
* (`f(ax)` and `f(bx)` are commonly known in advance.)
*
*
* tolerance = Defines an early termination condition. Receives the
* current upper and lower bounds on the root. The
* delegate must return `true` when these bounds are
* acceptable. If this function always returns `false`,
* full machine precision will be achieved.
*
* Returns:
*
* A tuple consisting of two ranges. The first two elements are the
* range (in `x`) of the root, while the second pair of elements
* are the corresponding function values at those points. If an exact
* root was found, both of the first two elements will contain the
* root, and the second pair of elements will be 0.
*/
Tuple!(T, T, R, R) findRoot(T, R, DF, DT)(scope DF f, in T ax, in T bx, in R fax, in R fbx,
scope DT tolerance) // = (T a, T b) => false)
if (
isFloatingPoint!T &&
is(typeof(tolerance(T.init, T.init)) : bool) &&
is(typeof(f(T.init)) == R) && isFloatingPoint!R
)
in
{
assert(!ax.isNaN() && !bx.isNaN(), "Limits must not be NaN");
assert(signbit(fax) != signbit(fbx), "Parameters must bracket the root.");
}
do
{
// Author: Don Clugston. This code is (heavily) modified from TOMS748
// (www.netlib.org). The changes to improve the worst-cast performance are
// entirely original.
T a, b, d; // [a .. b] is our current bracket. d is the third best guess.
R fa, fb, fd; // Values of f at a, b, d.
bool done = false; // Has a root been found?
// Allow ax and bx to be provided in reverse order
if (ax <= bx)
{
a = ax; fa = fax;
b = bx; fb = fbx;
}
else
{
a = bx; fa = fbx;
b = ax; fb = fax;
}
// Test the function at point c; update brackets accordingly
void bracket(T c)
{
R fc = f(c);
if (fc == 0 || fc.isNaN()) // Exact solution, or NaN
{
a = c;
fa = fc;
d = c;
fd = fc;
done = true;
return;
}
// Determine new enclosing interval
if (signbit(fa) != signbit(fc))
{
d = b;
fd = fb;
b = c;
fb = fc;
}
else
{
d = a;
fd = fa;
a = c;
fa = fc;
}
}
/* Perform a secant interpolation. If the result would lie on a or b, or if
a and b differ so wildly in magnitude that the result would be meaningless,
perform a bisection instead.
*/
static T secant_interpolate(T a, T b, R fa, R fb)
{
if (( ((a - b) == a) && b != 0) || (a != 0 && ((b - a) == b)))
{
// Catastrophic cancellation
if (a == 0)
a = copysign(T(0), b);
else if (b == 0)
b = copysign(T(0), a);
else if (signbit(a) != signbit(b))
return 0;
T c = ieeeMean(a, b);
return c;
}
// avoid overflow
if (b - a > T.max)
return b / 2 + a / 2;
if (fb - fa > R.max)
return a - (b - a) / 2;
T c = a - (fa / (fb - fa)) * (b - a);
if (c == a || c == b)
return (a + b) / 2;
return c;
}
/* Uses 'numsteps' newton steps to approximate the zero in [a .. b] of the
quadratic polynomial interpolating f(x) at a, b, and d.
Returns:
The approximate zero in [a .. b] of the quadratic polynomial.
*/
T newtonQuadratic(int numsteps)
{
// Find the coefficients of the quadratic polynomial.
immutable T a0 = fa;
immutable T a1 = (fb - fa)/(b - a);
immutable T a2 = ((fd - fb)/(d - b) - a1)/(d - a);
// Determine the starting point of newton steps.
T c = oppositeSigns(a2, fa) ? a : b;
// start the safeguarded newton steps.
foreach (int i; 0 .. numsteps)
{
immutable T pc = a0 + (a1 + a2 * (c - b))*(c - a);
immutable T pdc = a1 + a2*((2 * c) - (a + b));
if (pdc == 0)
return a - a0 / a1;
else
c = c - pc / pdc;
}
return c;
}
// On the first iteration we take a secant step:
if (fa == 0 || fa.isNaN())
{
done = true;
b = a;
fb = fa;
}
else if (fb == 0 || fb.isNaN())
{
done = true;
a = b;
fa = fb;
}
else
{
bracket(secant_interpolate(a, b, fa, fb));
}
// Starting with the second iteration, higher-order interpolation can
// be used.
int itnum = 1; // Iteration number
int baditer = 1; // Num bisections to take if an iteration is bad.