File Coverage

blib/lib/Data/Float.pm
Criterion Covered Total %
statement 232 268 86.5
branch 140 180 77.7
condition 33 39 84.6
subroutine 37 38 97.3
pod 21 21 100.0
total 463 546 84.8


line stmt bran cond sub pod time code
1             =head1 NAME
2              
3             Data::Float - details of the floating point data type
4              
5             =head1 SYNOPSIS
6              
7             use Data::Float qw(have_signed_zero);
8              
9             if(have_signed_zero) { ...
10              
11             # and many other constants; see text
12              
13             use Data::Float qw(
14             float_class float_is_normal float_is_subnormal
15             float_is_nzfinite float_is_zero float_is_finite
16             float_is_infinite float_is_nan);
17              
18             $class = float_class($value);
19              
20             if(float_is_normal($value)) { ...
21             if(float_is_subnormal($value)) { ...
22             if(float_is_nzfinite($value)) { ...
23             if(float_is_zero($value)) { ...
24             if(float_is_finite($value)) { ...
25             if(float_is_infinite($value)) { ...
26             if(float_is_nan($value)) { ...
27              
28             use Data::Float qw(float_sign signbit float_parts);
29              
30             $sign = float_sign($value);
31             $sign_bit = signbit($value);
32             ($sign, $exponent, $significand) = float_parts($value);
33              
34             use Data::Float qw(float_hex hex_float);
35              
36             print float_hex($value);
37             $value = hex_float($string);
38              
39             use Data::Float qw(float_id_cmp totalorder);
40              
41             @sorted_floats = sort { float_id_cmp($a, $b) } @floats;
42             if(totalorder($a, $b)) { ...
43              
44             use Data::Float qw(
45             pow2 mult_pow2 copysign nextup nextdown nextafter);
46              
47             $x = pow2($exp);
48             $x = mult_pow2($value, $exp);
49             $x = copysign($magnitude, $sign_from);
50             $x = nextup($x);
51             $x = nextdown($x);
52             $x = nextafter($x, $direction);
53              
54             =head1 DESCRIPTION
55              
56             This module is about the native floating point numerical data type.
57             A floating point number is one of the types of datum that can appear
58             in the numeric part of a Perl scalar. This module supplies constants
59             describing the native floating point type, classification functions,
60             and functions to manipulate floating point values at a low level.
61              
62             =head1 FLOATING POINT
63              
64             =head2 Classification
65              
66             Floating point values are divided into five subtypes:
67              
68             =over
69              
70             =item normalised
71              
72             The value is made up of a sign bit (making the value positive or
73             negative), a significand, and exponent. The significand is a number
74             in the range [1, 2), expressed as a binary fraction of a certain fixed
75             length. (Significands requiring a longer binary fraction, or lacking a
76             terminating binary representation, cannot be obtained.) The exponent
77             is an integer in a certain fixed range. The magnitude of the value
78             represented is the product of the significand and two to the power of
79             the exponent.
80              
81             =item subnormal
82              
83             The value is made up of a sign bit, significand, and exponent, as
84             for normalised values. However, the exponent is fixed at the minimum
85             possible for a normalised value, and the significand is in the range
86             (0, 1). The length of the significand is the same as for normalised
87             values. This is essentially a fixed-point format, used to provide
88             gradual underflow. Not all floating point formats support this subtype.
89             Where it is not supported, underflow is sudden, and the difference between
90             two minimum-exponent normalised values cannot be exactly represented.
91              
92             =item zero
93              
94             Depending on the floating point type, there may be either one or two
95             zero values: zeroes may carry a sign bit. Where zeroes are signed,
96             it is primarily in order to indicate the direction from which a value
97             underflowed (was rounded) to zero. Positive and negative zero compare
98             as numerically equal, and they give identical results in most arithmetic
99             operations. They are on opposite sides of some branch cuts in complex
100             arithmetic.
101              
102             =item infinite
103              
104             Some floating point formats include special infinite values. These are
105             generated by overflow, and by some arithmetic cases that mathematically
106             generate infinities. There are two infinite values: positive infinity
107             and negative infinity.
108              
109             Perl does not always generate infinite values when normal floating point
110             behaviour calls for it. For example, the division C<1.0/0.0> causes an
111             exception rather than returning an infinity.
112              
113             =item not-a-number (NaN)
114              
115             This type of value exists in some floating point formats to indicate
116             error conditions. Mathematically undefined operations may generate NaNs,
117             and NaNs propagate through all arithmetic operations. A NaN has the
118             distinctive property of comparing numerically unequal to all floating
119             point values, including itself.
120              
121             Perl does not always generate NaNs when normal floating point behaviour
122             calls for it. For example, the division C<0.0/0.0> causes an exception
123             rather than returning a NaN.
124              
125             Perl has only (at most) one NaN value, even if the underlying system
126             supports different NaNs. (IEEE 754 arithmetic has NaNs which carry a
127             quiet/signal bit, a sign bit (yes, a sign on a not-number), and many
128             bits of implementation-defined data.)
129              
130             =back
131              
132             =head2 Mixing floating point and integer values
133              
134             Perl does not draw a strong type distinction between native integer
135             (see L<Data::Integer>) and native floating point values. Both types
136             of value can be stored in the numeric part of a plain (string) scalar.
137             No distinction is made between the integer representation and the floating
138             point representation where they encode identical values. Thus, for
139             floating point arithmetic, native integer values that can be represented
140             exactly in floating point may be freely used as floating point values.
141              
142             Native integer arithmetic has exactly one zero value, which has no sign.
143             If the floating point type does not have signed zeroes then the floating
144             point and integer zeroes are exactly equivalent. If the floating point
145             type does have signed zeroes then the integer zero can still be used in
146             floating point arithmetic, and it behaves as an unsigned floating point
147             zero. On such systems there are therefore three types of zero available.
148             There is a bug in Perl which sometimes causes floating point zeroes to
149             change into integer zeroes; see L</BUGS> for details.
150              
151             Where a native integer value is used that is too large to exactly
152             represent in floating point, it will be rounded as necessary to a
153             floating point value. This rounding will occur whenever an operation
154             has to be performed in floating point because the result could not be
155             exactly represented as an integer. This may be confusing to functions
156             that expect a floating point argument.
157              
158             Similarly, some operations on floating point numbers will actually be
159             performed in integer arithmetic, and may result in values that cannot
160             be exactly represented in floating point. This happens whenever the
161             arguments have integer values that fit into the native integer type and
162             the mathematical result can be exactly represented as a native integer.
163             This may be confusing in cases where floating point semantics are
164             expected.
165              
166             See L<perlnumber(1)> for discussion of Perl's numeric semantics.
167              
168             =cut
169              
170             package Data::Float;
171              
172 9     9   561094 { use 5.006; }
  9         35  
173 9     9   55 use warnings;
  9         23  
  9         320  
174 9     9   53 use strict;
  9         34  
  9         275  
175              
176 9     9   56 use Carp qw(croak);
  9         26  
  9         609  
177              
178             our $VERSION = "0.013";
179              
180 9     9   2764 use parent "Exporter";
  9         2719  
  9         51  
181             our @EXPORT_OK = qw(
182             float_class float_is_normal float_is_subnormal float_is_nzfinite
183             float_is_zero float_is_finite float_is_infinite float_is_nan
184             float_sign signbit float_parts
185             float_hex hex_float
186             float_id_cmp totalorder
187             pow2 mult_pow2 copysign nextup nextdown nextafter
188             );
189             # constant functions get added to @EXPORT_OK later
190              
191             =head1 CONSTANTS
192              
193             =head2 Features
194              
195             =over
196              
197             =item have_signed_zero
198              
199             Truth value indicating whether floating point zeroes carry a sign. If yes,
200             then there are two floating point zero values: +0.0 and -0.0. (Perl
201             scalars can nevertheless also hold an integer zero, which is unsigned.)
202             If no, then there is only one zero value, which is unsigned.
203              
204             =item have_subnormal
205              
206             Truth value indicating whether there are subnormal floating point values.
207              
208             =item have_infinite
209              
210             Truth value indicating whether there are infinite floating point values.
211              
212             =item have_nan
213              
214             Truth value indicating whether there are NaN floating point values.
215              
216             It is difficult to reliably generate a NaN in Perl, so in some unlikely
217             circumstances it is possible that there might be NaNs that this module
218             failed to detect. In that case this constant would be false but a NaN
219             might still turn up somewhere. What this constant reliably indicates
220             is the availability of the C<nan> constant below.
221              
222             =back
223              
224             =head2 Extrema
225              
226             =over
227              
228             =item significand_bits
229              
230             The number of fractional bits in the significand of finite floating
231             point values. The significand also has an implicit integer bit, not
232             counted in this constant; the integer bit is always 1 for normalised
233             values and always 0 for subnormal values.
234              
235             =item significand_step
236              
237             The difference between adjacent representable values in the range [1, 2]
238             (where the exponent is zero). This is equal to 2^-significand_bits.
239              
240             =item max_finite_exp
241              
242             The maximum exponent permitted for finite floating point values.
243              
244             =item max_finite_pow2
245              
246             The maximum representable power of two. This is 2^max_finite_exp.
247              
248             =item max_finite
249              
250             The maximum representable finite value. This is 2^(max_finite_exp+1)
251             - 2^(max_finite_exp-significand_bits).
252              
253             =item max_number
254              
255             The maximum representable number. This is positive infinity if there
256             are infinite values, or max_finite if there are not.
257              
258             =item max_integer
259              
260             The maximum integral value for which all integers from zero to that
261             value inclusive are representable. Equivalently: the minimum positive
262             integral value N for which the value N+1 is not representable. This is
263             2^(significand_bits+1). The name is somewhat misleading.
264              
265             =item min_normal_exp
266              
267             The minimum exponent permitted for normalised floating point values.
268              
269             =item min_normal
270              
271             The minimum positive value representable as a normalised floating
272             point value. This is 2^min_normal_exp.
273              
274             =item min_finite_exp
275              
276             The base two logarithm of the minimum representable positive finite value.
277             If there are subnormals then this is min_normal_exp - significand_bits.
278             If there are no subnormals then this is min_normal_exp.
279              
280             =item min_finite
281              
282             The minimum representable positive finite value. This is
283             2^min_finite_exp.
284              
285             =back
286              
287             =head2 Special Values
288              
289             =over
290              
291             =item pos_zero
292              
293             The positive zero value. (Exists only if zeroes are signed, as indicated
294             by the C<have_signed_zero> constant.)
295              
296             If Perl is at risk of transforming floating point zeroes into integer
297             zeroes (see L</BUGS>), then this is actually a non-constant function
298             that always returns a fresh floating point zero. Thus the return value
299             is always a true floating point zero, regardless of what happened to
300             zeroes previously returned.
301              
302             =item neg_zero
303              
304             The negative zero value. (Exists only if zeroes are signed, as indicated
305             by the C<have_signed_zero> constant.)
306              
307             If Perl is at risk of transforming floating point zeroes into integer
308             zeroes (see L</BUGS>), then this is actually a non-constant function
309             that always returns a fresh floating point zero. Thus the return value
310             is always a true floating point zero, regardless of what happened to
311             zeroes previously returned.
312              
313             =item pos_infinity
314              
315             The positive infinite value. (Exists only if there are infinite values,
316             as indicated by the C<have_infinite> constant.)
317              
318             =item neg_infinity
319              
320             The negative infinite value. (Exists only if there are infinite values,
321             as indicated by the C<have_infinite> constant.)
322              
323             =item nan
324              
325             Not-a-number. (Exists only if NaN values were detected, as indicated
326             by the C<have_nan> constant.)
327              
328             =back
329              
330             =cut
331              
332             sub _mk_constant($$) {
333 162     162   345 my($name, $value) = @_;
334 9     9   1121 no strict "refs";
  9         21  
  9         7212  
335 162     0   951 *{__PACKAGE__."::".$name} = sub () { $value };
  162         849  
  0         0  
336 162         424 push @EXPORT_OK, $name;
337             }
338              
339             #
340             # mult_pow2() multiplies a specified value by a specified power of two.
341             # This is done using repeated multiplication, and can cope with cases
342             # where the power of two cannot be directly represented as a floating
343             # point value. (E.g., 0x1.b2p-900 can be multiplied by 2^1500 to get
344             # to 0x1.b2p+600; the input and output values can be represented in
345             # IEEE double, but 2^1500 cannot.) Overflow and underflow can occur.
346             #
347             # @powtwo is an array such that powtwo[i] = 2^2^i. Its elements are
348             # used in the repeated multiplication in mult_pow2. Similarly,
349             # @powhalf is such that powhalf[i] = 2^-2^i. Reading the exponent
350             # in binary indicates which elements of @powtwo/@powhalf to multiply
351             # by, except that it may indicate elements that don't exist, either
352             # because they're not representable or because the arrays haven't
353             # been filled yet. mult_pow2() will use the last element of the array
354             # repeatedly in this case. Thus array elements after the first are
355             # only an optimisation, and do not change behaviour.
356             #
357              
358             my @powtwo = (2.0);
359             my @powhalf = (0.5);
360              
361             sub mult_pow2($$) {
362 711     711 1 6145 my($value, $exp) = @_;
363 711 100       1556 return $_[0] if $value == 0.0;
364 632         951 my $powa = \@powtwo;
365 632 100       1202 if($exp < 0) {
366 368         553 $powa = \@powhalf;
367 368         549 $exp = -$exp;
368             }
369 632   100     2059 for(my $i = 0; $i != $#$powa && $exp != 0; $i++) {
370 3125 100       5590 $value *= $powa->[$i] if $exp & 1;
371 3125         8704 $exp >>= 1;
372             }
373 632         1291 $value *= $powa->[-1] while $exp--;
374 632         3843 return $value;
375             }
376              
377             #
378             # Range of finite exponent values.
379             #
380              
381             my $min_finite_exp;
382             my $max_finite_exp;
383             my $max_finite_pow2;
384             my $min_finite;
385              
386             my @directions = (
387             {
388             expsign => -1,
389             powa => \@powhalf,
390             xexp => \$min_finite_exp,
391             xpower => \$min_finite,
392             },
393             {
394             expsign => +1,
395             powa => \@powtwo,
396             xexp => \$max_finite_exp,
397             xpower => \$max_finite_pow2,
398             },
399             );
400              
401             while(!$directions[0]->{done} || !$directions[1]->{done}) {
402             foreach my $direction (@directions) {
403             next if $direction->{done};
404             my $lastpow = $direction->{powa}->[-1];
405             my $nextpow = $lastpow * $lastpow;
406             unless(mult_pow2($nextpow, -$direction->{expsign} *
407             (1 << (@{$direction->{powa}} - 1)))
408             == $lastpow) {
409             $direction->{done} = 1;
410             next;
411             }
412             push @{$direction->{powa}}, $nextpow;
413             }
414             }
415              
416             foreach my $direction (@directions) {
417             my $expsign = $direction->{expsign};
418             my $xexp = 1 << (@{$direction->{powa}} - 1);
419             my $extremum = $direction->{powa}->[-1];
420             for(my $addexp = $xexp; $addexp >>= 1; ) {
421             my $nx = mult_pow2($extremum, $expsign*$addexp);
422             if(mult_pow2($nx, -$expsign*$addexp) == $extremum) {
423             $xexp += $addexp;
424             $extremum = $nx;
425             }
426             }
427             ${$direction->{xexp}} = $expsign * $xexp;
428             ${$direction->{xpower}} = $extremum;
429             }
430              
431             _mk_constant("min_finite_exp", $min_finite_exp);
432             _mk_constant("min_finite", $min_finite);
433             _mk_constant("max_finite_exp", $max_finite_exp);
434             _mk_constant("max_finite_pow2", $max_finite_pow2);
435              
436             #
437             # pow2() generates a power of two from scratch. It complains if given
438             # an exponent that would make an unrepresentable value.
439             #
440              
441             sub pow2($) {
442 39     39 1 696 my($exp) = @_;
443 39 100 100     422 croak "exponent $exp out of range [$min_finite_exp, $max_finite_exp]"
444             unless $exp >= $min_finite_exp && $exp <= $max_finite_exp;
445 37         114 return mult_pow2(1.0, $exp);
446             }
447              
448             #
449             # Significand size.
450             #
451              
452             my($significand_bits, $significand_step);
453             {
454             my $i;
455             for($i = 1; ; $i++) {
456             my $tryeps = $powhalf[$i];
457             last unless (1.0 + $tryeps) - 1.0 == $tryeps;
458             }
459             $i--;
460             $significand_bits = 1 << $i;
461             $significand_step = $powhalf[$i];
462             while($i--) {
463             my $tryeps = $significand_step * $powhalf[$i];
464             if((1.0 + $tryeps) - 1.0 == $tryeps) {
465             $significand_bits += 1 << $i;
466             $significand_step = $tryeps;
467             }
468             }
469             }
470              
471             _mk_constant("significand_bits", $significand_bits);
472             _mk_constant("significand_step", $significand_step);
473              
474             my $max_finite = $max_finite_pow2 -
475             pow2($max_finite_exp - $significand_bits - 1);
476             $max_finite += $max_finite;
477              
478             my $max_integer = pow2($significand_bits + 1);
479              
480             _mk_constant("max_finite", $max_finite);
481             _mk_constant("max_integer", $max_integer);
482              
483             #
484             # Subnormals.
485             #
486              
487             my $have_subnormal;
488             {
489             my $testval = $min_finite * 1.5;
490             $have_subnormal = $testval == $min_finite ||
491             $testval == ($min_finite + $min_finite);
492             }
493              
494             _mk_constant("have_subnormal", $have_subnormal);
495              
496             my $min_normal_exp = $have_subnormal ?
497             $min_finite_exp + $significand_bits :
498             $min_finite_exp;
499             my $min_normal = $have_subnormal ?
500             mult_pow2($min_finite, $significand_bits) :
501             $min_finite;
502              
503             _mk_constant("min_normal_exp", $min_normal_exp);
504             _mk_constant("min_normal", $min_normal);
505              
506             #
507             # Feature tests.
508             #
509              
510             my $have_signed_zero = sprintf("%e", -0.0) =~ /\A-/;
511             _mk_constant("have_signed_zero", $have_signed_zero);
512             my($pos_zero, $neg_zero);
513             if($have_signed_zero) {
514             $pos_zero = +0.0;
515             $neg_zero = -0.0;
516             my $tzero = -0.0;
517 9     9   75 { no warnings "void"; $tzero == $tzero; }
  9         21  
  9         3996  
518             my $ntzero = -$tzero;
519             if(sprintf("%e", -$ntzero) =~ /\A-/) {
520             _mk_constant("pos_zero", $pos_zero);
521             _mk_constant("neg_zero", $neg_zero);
522             } else {
523             # Zeroes lose their signedness upon arithmetic operations.
524             # Therefore make the pos_zero and neg_zero functions
525             # return fresh zeroes to avoid trouble.
526 2     2   10132 *pos_zero = sub () { my $ret = $pos_zero };
527 3     3   151 *neg_zero = sub () { my $ret = $neg_zero };
528             push @EXPORT_OK, "pos_zero", "neg_zero";
529             }
530             }
531              
532             my($have_infinite, $pos_infinity, $neg_infinity);
533             {
534             my $testval = $max_finite * $max_finite;
535             $have_infinite = $testval == $testval && $testval != $max_finite;
536             _mk_constant("have_infinite", $have_infinite);
537             if($have_infinite) {
538             _mk_constant("pos_infinity", $pos_infinity = $testval);
539             _mk_constant("neg_infinity", $neg_infinity = -$testval);
540             }
541             }
542              
543             my $max_number = $have_infinite ? $pos_infinity : $max_finite;
544             _mk_constant("max_number", $max_number);
545              
546             my($have_nan, $nan);
547             foreach my $nan_formula (
548             '$have_infinite && $pos_infinity/$pos_infinity',
549             'log(-1.0)',
550             '0.0/0.0',
551             '"nan"') {
552             my $maybe_nan =
553             eval 'local $SIG{__DIE__}; local $SIG{__WARN__} = sub { }; '.
554             $nan_formula;
555             if(do { local $SIG{__WARN__} = sub { }; $maybe_nan != $maybe_nan }) {
556             $have_nan = 1;
557             $nan = $maybe_nan;
558             _mk_constant("nan", $nan);
559             last;
560             }
561             }
562             _mk_constant("have_nan", $have_nan);
563              
564             # The rest of the code is parsed after the constants have been calculated
565             # and installed, so that it can benefit from their constancy.
566             {
567             local $/ = undef;
568             my $code = <DATA>;
569             close(DATA);
570             {
571             local $SIG{__DIE__};
572 9 50 66 9 1 88 eval $code;
  9 100 100 9 1 21  
  9 100 100 9 1 19  
  9 100 100 9 1 21  
  9 100 66 9 1 20  
  9 100 100 268 1 30  
  9 100 100 39 1 19  
  9 100 0 42 1 933  
  9 100 100 41 1 67  
  9 100 100 162 1 22  
  9 100 66 14 1 628  
  9 100   96 1 3686  
  9 100   402 1 383  
  9 100   14 1 49  
  9 100   76 1 557  
  9 100   14 1 19  
  9 50   174 1 19  
  9 100   62 1 12735  
  9 0   28 1 78  
  9 0   54   20  
  9 50   22   46  
  268 50   17   443  
  268 100   33   507  
  268 100   140   879  
  39 0   81   7112  
  39 50       75  
  37 50       75  
  37 50       132  
  42 50       6805  
  42 100       156  
  24 50       53  
  21 100       46  
  21 100       51  
  15 100       74  
  41 100       4255  
  41 50       125  
  39 100       63  
  39 50       52  
  39 100       114  
  2 100       8  
  4 100       11  
  2 100       8  
  2 100       28  
  35 100       52  
  35 50       80  
  6 100       16  
  6 100       11  
  6 100       30  
  4 100       9  
  4 100       9  
  1 100       2  
  1 50       3  
  0 100       0  
  2 100       4  
  29 100       53  
  31 100       72  
  31 100       87  
  0 100       0  
  0 0       0  
  0 50       0  
  0 50       0  
  0 50       0  
  0 50       0  
  0 0       0  
  31 0       54  
  31 0       67  
  62 0       84  
  62 0       85  
  62 0       179  
  62 50       124  
  31 100       170  
  31 100       74  
  31 100       66  
  31 100       40  
  31 50       48  
  31 100       93  
  62 100       116  
  62 100       106  
  62 100       154  
  32 100       66  
  62 50       164  
  0 100       0  
  62 100       208  
  31 100       84  
  31 100       82  
  31 100       98  
  11         30  
  4         16  
  4         35  
  2         5  
  2         6  
  2         5  
  2         6  
  2         8  
  2         37  
  1         4  
  1         3  
  31         62  
  31         61  
  31         78  
  2         8  
  0         0  
  31         179  
  31         84  
  162         10987  
  162         364  
  18         42  
  16         61  
  8         24  
  120         640  
  14         1492  
  14         65  
  96         1610  
  96         156  
  96         629  
  402         2258  
  402         1278  
  14         2293  
  76         1713  
  76         406  
  14         1597  
  174         1706  
  174         558  
  62         8037  
  62         123  
  62         117  
  62         146  
  19         28  
  19         28  
  62         124  
  5         17  
  57         97  
  57         162  
  7         22  
  77         86  
  77         142  
  10         15  
  10         27  
  7         19  
  7         11  
  27         77  
  270         373  
  270         552  
  70         123  
  70         205  
  57         192  
  28         13940  
  28         70  
  28         50  
  54         4586  
  54         430  
  18         65  
  18         34  
  18         39  
  18         35  
  18         32  
  18         45  
  18         38  
  6         12  
  6         22  
  12         25  
  12         16  
  12         38  
  12         55  
  12         32  
  12         27  
  12         16  
  12         28  
  0         0  
  0         0  
  0         0  
  0         0  
  0         0  
  12         16  
  12         15  
  12         23  
  12         26  
  0         0  
  0         0  
  0         0  
  0         0  
  0         0  
  0         0  
  0         0  
  0         0  
  0         0  
  0         0  
  0         0  
  0         0  
  0         0  
  0         0  
  0         0  
  0         0  
  0         0  
  12         18  
  12         26  
  15         46  
  12         30  
  18         91  
  18         34  
  18         131  
  18         35  
  18         79  
  0         0  
  22         6332  
  22         112  
  15         49  
  17         786  
  33         3484  
  33         153  
  28         79  
  24         73  
  16         31  
  16         36  
  8         15  
  8         21  
  4         34  
  0         0  
  0         0  
  8         24  
  2         3  
  2         2  
  8         12  
  12         27  
  140         245  
  140         658  
  81         317  
573             }
574             die $@ if $@ ne "";
575             }
576              
577             1;
578              
579             __DATA__
580              
581             =head1 FUNCTIONS
582              
583             Each "float_" function takes a floating point argument to operate on. The
584             argument must be a native floating point value, or a native integer with
585             a value that can be represented in floating point. Giving a non-numeric
586             argument will cause mayhem. See L<Params::Classify/is_number> for a way
587             to check for numericness. Only the numeric value of the scalar is used;
588             the string value is completely ignored, so dualvars are not a problem.
589              
590             =head2 Classification
591              
592             Each "float_is_" function returns a simple truth value result.
593              
594             =over
595              
596             =item float_class(VALUE)
597              
598             Determines which of the five classes described above VALUE falls
599             into. Returns "NORMAL", "SUBNORMAL", "ZERO", "INFINITE", or "NAN"
600             accordingly.
601              
602             =cut
603              
604             sub float_class($) {
605             my($val) = @_;
606             return "ZERO" if $val == 0.0;
607             return "NAN" if $val != $val;
608             $val = -$val if $val < 0;
609             return "INFINITE" if have_infinite && $val == $pos_infinity;
610             return have_subnormal && $val < min_normal ? "SUBNORMAL" : "NORMAL";
611             }
612              
613             =item float_is_normal(VALUE)
614              
615             Returns true iff VALUE is a normalised floating point value.
616              
617             =cut
618              
619             sub float_is_normal($) { float_class($_[0]) eq "NORMAL" }
620              
621             =item float_is_subnormal(VALUE)
622              
623             Returns true iff VALUE is a subnormal floating point value.
624              
625             =cut
626              
627             sub float_is_subnormal($) { float_class($_[0]) eq "SUBNORMAL" }
628              
629             =item float_is_nzfinite(VALUE)
630              
631             Returns true iff VALUE is a non-zero finite value (either normal or
632             subnormal; not zero, infinite, or NaN).
633              
634             =cut
635              
636             sub float_is_infinite($);
637              
638             sub float_is_nzfinite($) {
639             my($val) = @_;
640             return $val != 0.0 && $val == $val && !float_is_infinite($val);
641             }
642              
643             =item float_is_zero(VALUE)
644              
645             Returns true iff VALUE is a zero. If zeroes are signed then the sign
646             is irrelevant.
647              
648             =cut
649              
650             sub float_is_zero($) {
651             my($val) = @_;
652             return $val == 0.0;
653             }
654              
655             =item float_is_finite(VALUE)
656              
657             Returns true iff VALUE is a finite value (either normal, subnormal,
658             or zero; not infinite or NaN).
659              
660             =cut
661              
662             sub float_is_finite($) {
663             my($val) = @_;
664             return $val == $val && !float_is_infinite($val);
665             }
666              
667             =item float_is_infinite(VALUE)
668              
669             Returns true iff VALUE is an infinity (either positive infinity or
670             negative infinity).
671              
672             =cut
673              
674             sub float_is_infinite($) {
675             return undef unless have_infinite;
676             my($val) = @_;
677             return $val == $pos_infinity || $val == $neg_infinity;
678             }
679              
680             =item float_is_nan(VALUE)
681              
682             Returns true iff VALUE is a NaN.
683              
684             =cut
685              
686             sub float_is_nan($) {
687             my($val) = @_;
688             return $val != $val;
689             }
690              
691             =back
692              
693             =head2 Examination
694              
695             =over
696              
697             =item float_sign(VALUE)
698              
699             Returns "B<+>" or "B<->" to indicate the sign of VALUE. An unsigned
700             zero returns the sign "B<+>". C<die>s if VALUE is a NaN.
701              
702             =cut
703              
704             sub signbit($);
705              
706             sub float_sign($) {
707             my($val) = @_;
708             croak "can't get sign of a NaN" if $val != $val;
709             return signbit($val) ? "-" : "+";
710             }
711              
712             =item signbit(VALUE)
713              
714             VALUE must be a floating point value. Returns the sign bit of VALUE:
715             0 if VALUE is positive or a positive or unsigned zero, or 1 if VALUE is
716             negative or a negative zero. Returns an unpredictable value if VALUE
717             is a NaN.
718              
719             This is an IEEE 754 standard function. According to the standard NaNs
720             have a well-behaved sign bit, but Perl can't see that bit.
721              
722             =cut
723              
724             sub signbit($) {
725             my($val) = @_;
726             return (have_signed_zero && $val == 0.0 ?
727             sprintf("%+.f", $val) eq "-0" : $val < 0.0) ? 1 : 0;
728             }
729              
730             =item float_parts(VALUE)
731              
732             Divides up a non-zero finite floating point value into sign, exponent,
733             and significand, returning these as a three-element list in that order.
734             The significand is returned as a floating point value, in the range
735             [1, 2) for normalised values, and in the range (0, 1) for subnormals.
736             C<die>s if VALUE is not finite and non-zero.
737              
738             =cut
739              
740             sub float_parts($) {
741             my($val) = @_;
742             croak "$val is not non-zero finite" unless float_is_nzfinite($val);
743             my $sign = "+";
744             if($val < 0.0) {
745             $sign = "-";
746             $val = -$val;
747             }
748             if(have_subnormal && $val < min_normal) {
749             return ($sign, min_normal_exp,
750             mult_pow2($val, -(min_normal_exp)));
751             }
752             my $exp = 0;
753             if($val < 1.0) {
754             for(my $i = @powhalf; $i--; ) {
755             $exp <<= 1;
756             if($val < $powhalf[$i]) {
757             $exp |= 1;
758             $val = mult_pow2($val, 1 << $i);
759             }
760             }
761             $val *= 2.0;
762             $exp = -1-$exp;
763             } elsif($val >= 2.0) {
764             for(my $i = @powtwo; $i--; ) {
765             $exp <<= 1;
766             if($val >= $powtwo[$i]) {
767             $exp |= 1;
768             $val = mult_pow2($val, -(1 << $i));
769             }
770             }
771             }
772             return ($sign, $exp, $val);
773             }
774              
775             =back
776              
777             =head2 String conversion
778              
779             =over
780              
781             =item float_hex(VALUE[, OPTIONS])
782              
783             Encodes the exact value of VALUE as a hexadecimal fraction, returning
784             the fraction as a string. Specifically, for finite values the output is
785             of the form "I<s>B<0x>I<m>B<.>I<mmmmm>B<p>I<eee>", where "I<s>" is the
786             sign, "I<m>B<.>I<mmmm>" is the significand in hexadecimal, and "I<eee>"
787             is the exponent in decimal with a sign.
788              
789             The details of the output format are very configurable. If OPTIONS
790             is supplied, it must be a reference to a hash, in which these keys may
791             be present:
792              
793             =over
794              
795             =item B<exp_digits>
796              
797             The number of digits of exponent to show, unless this is modified by
798             B<exp_digits_range_mod> or more are required to show the exponent exactly.
799             (The exponent is always shown in full.) Default 0, so the minimum
800             possible number of digits is used.
801              
802             =item B<exp_digits_range_mod>
803              
804             Modifies the number of exponent digits to show, based on the number of
805             digits required to show the full range of exponents for normalised and
806             subnormal values. If "B<IGNORE>" then nothing is done. If "B<ATLEAST>"
807             then at least this many digits are shown. Default "B<IGNORE>".
808              
809             =item B<exp_neg_sign>
810              
811             The string that is prepended to a negative exponent. Default "B<->".
812              
813             =item B<exp_pos_sign>
814              
815             The string that is prepended to a non-negative exponent. Default "B<+>".
816             Make it the empty string to suppress the positive sign.
817              
818             =item B<frac_digits>
819              
820             The number of fractional digits to show, unless this is modified by
821             B<frac_digits_bits_mod> or B<frac_digits_value_mod>. Default 0, but by
822             default this gets modified.
823              
824             =item B<frac_digits_bits_mod>
825              
826             Modifies the number of fractional digits to show, based on the length of
827             the significand. There is a certain number of digits that is the minimum
828             required to explicitly state every bit that is stored, and the number
829             of digits to show might get set to that number depending on this option.
830             If "B<IGNORE>" then nothing is done. If "B<ATLEAST>" then at least this
831             many digits are shown. If "B<ATMOST>" then at most this many digits
832             are shown. If "B<EXACTLY>" then exactly this many digits are shown.
833             Default "B<ATLEAST>".
834              
835             =item B<frac_digits_value_mod>
836              
837             Modifies the number of fractional digits to show, based on the number
838             of digits required to show the actual value exactly. Works the same
839             way as B<frac_digits_bits_mod>. Default "B<ATLEAST>".
840              
841             =item B<hex_prefix_string>
842              
843             The string that is prefixed to hexadecimal digits. Default "B<0x>".
844             Make it the empty string to suppress the prefix.
845              
846             =item B<infinite_string>
847              
848             The string that is returned for an infinite magnitude. Default "B<inf>".
849              
850             =item B<nan_string>
851              
852             The string that is returned for a NaN value. Default "B<nan>".
853              
854             =item B<neg_sign>
855              
856             The string that is prepended to a negative value (including negative
857             zero). Default "B<->".
858              
859             =item B<pos_sign>
860              
861             The string that is prepended to a positive value (including positive or
862             unsigned zero). Default "B<+>". Make it the empty string to suppress
863             the positive sign.
864              
865             =item B<subnormal_strategy>
866              
867             The manner in which subnormal values are displayed. If "B<SUBNORMAL>",
868             they are shown with the minimum exponent for normalised values and
869             a significand in the range (0, 1). This matches how they are stored
870             internally. If "B<NORMAL>", they are shown with a significand in the
871             range [1, 2) and a lower exponent, as if they were normalised. This gives
872             a consistent appearance for magnitudes regardless of normalisation.
873             Default "B<SUBNORMAL>".
874              
875             =item B<zero_strategy>
876              
877             The manner in which zero values are displayed. If "B<STRING=>I<str>",
878             the string I<str> is used, preceded by a sign. If "B<SUBNORMAL>",
879             it is shown with significand zero and the minimum normalised exponent.
880             If "B<EXPONENT=>I<exp>", it is shown with significand zero and exponent
881             I<exp>. Default "B<STRING=0.0>". An unsigned zero is treated as having
882             a positive sign.
883              
884             =back
885              
886             =cut
887              
888             my %float_hex_defaults = (
889             infinite_string => "inf",
890             nan_string => "nan",
891             exp_neg_sign => "-",
892             exp_pos_sign => "+",
893             pos_sign => "+",
894             neg_sign => "-",
895             hex_prefix_string => "0x",
896             subnormal_strategy => "SUBNORMAL",
897             zero_strategy => "STRING=0.0",
898             frac_digits => 0,
899             frac_digits_bits_mod => "ATLEAST",
900             frac_digits_value_mod => "ATLEAST",
901             exp_digits => 0,
902             exp_digits_range_mod => "IGNORE",
903             );
904              
905             sub _float_hex_option($$) {
906             my($options, $name) = @_;
907             my $val = defined($options) ? $options->{$name} : undef;
908             return defined($val) ? $val : $float_hex_defaults{$name};
909             }
910              
911             use constant exp_digits_range => do {
912             my $minexp = min_normal_exp - significand_bits;
913             my $maxexp = max_finite_exp + 1;
914             my $len_minexp = length(-$minexp);
915             my $len_maxexp = length($maxexp);
916             $len_minexp > $len_maxexp ? $len_minexp : $len_maxexp;
917             };
918             use constant frac_digits_bits => (significand_bits + 3) >> 2;
919             use constant frac_sections => do { use integer; (frac_digits_bits + 6) / 7; };
920              
921             sub float_hex($;$) {
922             my($val, $options) = @_;
923             return _float_hex_option($options, "nan_string") if $val != $val;
924             if(have_infinite) {
925             my $inf_sign;
926             if($val == $pos_infinity) {
927             $inf_sign = _float_hex_option($options, "pos_sign");
928             EMIT_INFINITY:
929             return $inf_sign.
930             _float_hex_option($options, "infinite_string");
931             } elsif($val == $neg_infinity) {
932             $inf_sign = _float_hex_option($options, "neg_sign");
933             goto EMIT_INFINITY;
934             }
935             }
936             my($sign, $exp, $sgnf);
937             if($val == 0.0) {
938             $sign = float_sign($val);
939             my $strat = _float_hex_option($options, "zero_strategy");
940             if($strat =~ /\ASTRING=(.*)\z/s) {
941             my $string = $1;
942             return _float_hex_option($options,
943             $sign eq "-" ? "neg_sign" : "pos_sign").
944             $string;
945             } elsif($strat eq "SUBNORMAL") {
946             $exp = min_normal_exp;
947             } elsif($strat =~ /\AEXPONENT=([-+]?[0-9]+)\z/) {
948             $exp = $1;
949             } else {
950             croak "unrecognised zero strategy `$strat'";
951             }
952             $sgnf = 0.0;
953             } else {
954             ($sign, $exp, $sgnf) = float_parts($val);
955             }
956             my $digits = int($sgnf);
957             if($digits eq "0" && $sgnf != 0.0) {
958             my $strat = _float_hex_option($options, "subnormal_strategy");
959             if($strat eq "NORMAL") {
960             my $add_exp;
961             (undef, $add_exp, $sgnf) = float_parts($sgnf);
962             $exp += $add_exp;
963             $digits = "1";
964             } elsif($strat eq "SUBNORMAL") {
965             # do nothing extra
966             } else {
967             croak "unrecognised subnormal strategy `$strat'";
968             }
969             }
970             $sgnf -= $digits;
971             for(my $i = frac_sections; $i--; ) {
972             $sgnf *= 268435456.0;
973             my $section = int($sgnf);
974             $digits .= sprintf("%07x", $section);
975             $sgnf -= $section;
976             }
977             $digits =~ s/(.)0+\z/$1/;
978             my $ndigits = 1 + _float_hex_option($options, "frac_digits");
979             croak "negative number of digits requested" if $ndigits <= 0;
980             my $mindigits = 1;
981             my $maxdigits = $ndigits + frac_digits_bits;
982             foreach my $constraint (["frac_digits_bits_mod", 1+frac_digits_bits],
983             ["frac_digits_value_mod", length($digits)]) {
984             my($optname, $number) = @$constraint;
985             my $mod = _float_hex_option($options, $optname);
986             if($mod =~ /\A(?:ATLEAST|EXACTLY)\z/) {
987             $mindigits = $number if $mindigits < $number;
988             }
989             if($mod =~ /\A(?:ATMOST|EXACTLY)\z/) {
990             $maxdigits = $number if $maxdigits > $number;
991             }
992             croak "unrecognised length modification setting `$mod'"
993             unless $mod =~ /\A(?:AT(?:MO|LEA)ST|EXACTLY|IGNORE)\z/;
994             }
995             croak "incompatible length constraints" if $maxdigits < $mindigits;
996             $ndigits = $ndigits < $mindigits ? $mindigits :
997             $ndigits > $maxdigits ? $maxdigits : $ndigits;
998             if($ndigits > length($digits)) {
999             $digits .= "0" x ($ndigits - length($digits));
1000             } elsif($ndigits < length($digits)) {
1001             my $chopped = substr($digits, $ndigits, length($digits), "");
1002             if($chopped =~ /\A[89abcdef]/ &&
1003             !($chopped =~ /\A80*\z/ &&
1004             $digits =~ /[02468ace]\z/)) {
1005             for(my $i = length($digits) - 1; ; ) {
1006             my $d = substr($digits, $i, 1);
1007             $d =~ tr/0-9a-f/1-9a-f0/;
1008             substr($digits, $i, 1, $d);
1009             last unless $d eq "0";
1010             }
1011             if($digits =~ /\A2/) {
1012             $exp++;
1013             substr($digits, 0, 1, "1");
1014             }
1015             }
1016             }
1017             my $nexpdigits = _float_hex_option($options, "exp_digits");
1018             my $mod = _float_hex_option($options, "exp_digits_range_mod");
1019             if($mod eq "ATLEAST") {
1020             $nexpdigits = exp_digits_range
1021             if $nexpdigits < exp_digits_range;
1022             } elsif($mod ne "IGNORE") {
1023             croak "unrecognised exponent length ".
1024             "modification setting `$mod'";
1025             }
1026             $digits =~ s/\A(.)(.)/$1.$2/;
1027             return sprintf("%s%s%sp%s%0*d",
1028             _float_hex_option($options,
1029             $sign eq "-" ? "neg_sign" : "pos_sign"),
1030             _float_hex_option($options, "hex_prefix_string"),
1031             $digits,
1032             _float_hex_option($options,
1033             $exp < 0 ? "exp_neg_sign" : "exp_pos_sign"),
1034             $nexpdigits, abs($exp));
1035             }
1036              
1037             =item hex_float(STRING)
1038              
1039             Generates and returns a floating point value from a string
1040             encoding it in hexadecimal. The standard input form is
1041             "[I<s>][B<0x>]I<m>[B<.>I<mmmmm>][B<p>I<eee>]", where "I<s>" is the sign,
1042             "I<m>[B<.>I<mmmm>]" is a (fractional) hexadecimal number, and "I<eee>"
1043             an optionally-signed exponent in decimal. If present, the exponent
1044             identifies a power of two (not sixteen) by which the given fraction will
1045             be multiplied.
1046              
1047             If the value given in the string cannot be exactly represented in the
1048             floating point type because it has too many fraction bits, the nearest
1049             representable value is returned, with ties broken in favour of the value
1050             with a zero low-order bit. If the value given is too large to exactly
1051             represent then an infinity is returned, or the largest finite value if
1052             there are no infinities.
1053              
1054             Additional input formats are accepted for special values.
1055             "[I<s>]B<inf>[B<inity>]" returns an infinity, or C<die>s if there are
1056             no infinities. "[I<s>][B<s>]B<nan>" returns a NaN, or C<die>s if there
1057             are no NaNs available.
1058              
1059             All input formats are understood case insensitively. The function
1060             correctly interprets all possible outputs from C<float_hex> with default
1061             settings.
1062              
1063             =cut
1064              
1065             sub hex_float($) {
1066             my($str) = @_;
1067             if($str =~ /\A([-+]?)(?:0x)?([0-9a-f]+)(?:\.([0-9a-f]+)+)?
1068             (?:p([-+]?[0-9]+))?\z/xi) {
1069             my($sign, $digits, $frac_digits, $in_exp) = ($1, $2, $3, $4);
1070             my $value;
1071             $frac_digits = "" unless defined $frac_digits;
1072             $in_exp = "0" unless defined $in_exp;
1073             $digits .= $frac_digits;
1074             $digits =~ s/\A0+//;
1075             if($digits eq "") {
1076             $value = 0.0;
1077             goto GOT_MAG;
1078             }
1079             my $digit_exp = (length($digits) - length($frac_digits)) * 4;
1080             my @limbs;
1081             push @limbs, hex($1) while $digits =~ /(.{7})/sgc;
1082             push @limbs, hex(substr($1."000000", 0, 7))
1083             if $digits =~ /(.+)/sg;
1084             my $skip_bits = $limbs[0] < 0x4000000 ?
1085             $limbs[0] < 0x2000000 ? 3 : 2 :
1086             $limbs[0] < 0x8000000 ? 1 : 0;
1087             my $val_exp = $digit_exp - $skip_bits - 1 + $in_exp;
1088             my $sig_bits;
1089             if($val_exp > max_finite_exp) {
1090             $value = have_infinite ? Data::Float::pos_infinity() :
1091             max_finite;
1092             goto GOT_MAG;
1093             } elsif($val_exp < min_finite_exp-1) {
1094             $value = 0.0;
1095             goto GOT_MAG;
1096             } elsif($val_exp < min_normal_exp) {
1097             $sig_bits = $val_exp - (min_finite_exp-1);
1098             } else {
1099             $sig_bits = significand_bits+1;
1100             }
1101             my $gbit_lpos = do { use integer; ($skip_bits+$sig_bits)/28 };
1102             if(@limbs > $gbit_lpos) {
1103             my $gbit_bpos = 27 - ($skip_bits + $sig_bits) % 28;
1104             my $sbit = 0;
1105             while(@limbs > $gbit_lpos+1) {
1106             $sbit = 1 if pop(@limbs) != 0;
1107             }
1108             my $gbit_mask = 1 << $gbit_bpos;
1109             my $sbit_mask = $gbit_mask - 1;
1110             if($limbs[$gbit_lpos] & $sbit_mask) {
1111             $sbit = 1;
1112             $limbs[$gbit_lpos] &= ~$sbit_mask;
1113             }
1114             if($limbs[$gbit_lpos] & $gbit_mask) {
1115             unless($sbit) {
1116             if($gbit_bpos == 27 &&
1117             $gbit_lpos != 0) {
1118             $sbit = $limbs[$gbit_lpos - 1]
1119             & 1;
1120             } else {
1121             $sbit = $limbs[$gbit_lpos] &
1122             ($gbit_mask << 1);
1123             }
1124             }
1125             if($sbit) {
1126             $limbs[$gbit_lpos] += $gbit_mask;
1127             } else {
1128             $limbs[$gbit_lpos] -= $gbit_mask;
1129             }
1130             }
1131             }
1132             $value = 0.0;
1133             for(my $i = @limbs; $i--; ) {
1134             $value += mult_pow2($limbs[$i], -28*($i+1));
1135             }
1136             $value = mult_pow2($value, $in_exp + $digit_exp);
1137             GOT_MAG:
1138             return $sign eq "-" ? -$value : $value;
1139             } elsif($str =~ /\A([-+]?)inf(?:inity)?\z/i) {
1140             croak "infinite values not available" unless have_infinite;
1141             return $1 eq "-" ? Data::Float::neg_infinity() :
1142             Data::Float::pos_infinity();
1143             } elsif($str =~ /\A([-+]?)s?nan\z/si) {
1144             croak "Nan value not available" unless have_nan;
1145             return Data::Float::nan();
1146             } else {
1147             croak "bad syntax for hexadecimal floating point value";
1148             }
1149             }
1150              
1151             =back
1152              
1153             =head2 Comparison
1154              
1155             =over
1156              
1157             =item float_id_cmp(A, B)
1158              
1159             This is a comparison function supplying a total ordering of floating
1160             point values. A and B must both be floating point values. Returns -1,
1161             0, or +1, indicating whether A is to be sorted before, the same as,
1162             or after B.
1163              
1164             The ordering is of the identities of floating point values, not their
1165             numerical values. If zeroes are signed, then the two types are considered
1166             to be distinct. NaNs compare equal to each other, but different from
1167             all numeric values. The exact ordering provided is mostly numerical
1168             order: NaNs come first, followed by negative infinity, then negative
1169             finite values, then negative zero, then positive (or unsigned) zero,
1170             then positive finite values, then positive infinity.
1171              
1172             In addition to sorting, this function can be useful to check for a zero
1173             of a particular sign.
1174              
1175             =cut
1176              
1177             sub float_id_cmp($$) {
1178             my($a, $b) = @_;
1179             if(float_is_nan($a)) {
1180             return float_is_nan($b) ? 0 : -1;
1181             } elsif(float_is_nan($b)) {
1182             return +1;
1183             } elsif(float_is_zero($a) && float_is_zero($b)) {
1184             return signbit($b) - signbit($a);
1185             } else {
1186             return $a <=> $b;
1187             }
1188             }
1189              
1190             =item totalorder(A, B)
1191              
1192             This is a comparison function supplying a total ordering of floating point
1193             values. A and B must both be floating point values. Returns a truth value
1194             indicating whether A is to be sorted before-or-the-same-as B. That is,
1195             it is a <= predicate on the total ordering. The ordering is the same as
1196             that provided by C<float_id_cmp>: NaNs come first, followed by negative
1197             infinity, then negative finite values, then negative zero, then positive
1198             (or unsigned) zero, then positive finite values, then positive infinity.
1199              
1200             This is an IEEE 754r standard function. According to the standard it
1201             is meant to distinguish different kinds of NaNs, based on their sign
1202             bit, quietness, and payload, but this function (like the rest of Perl)
1203             perceives only one NaN.
1204              
1205             =cut
1206              
1207             sub totalorder($$) { float_id_cmp($_[0], $_[1]) <= 0 }
1208              
1209             =back
1210              
1211             =head2 Manipulation
1212              
1213             =over
1214              
1215             =item pow2(EXP)
1216              
1217             EXP must be an integer. Returns the value two the the power EXP.
1218             C<die>s if that value cannot be represented exactly as a floating
1219             point value. The return value may be either normalised or subnormal.
1220              
1221             =item mult_pow2(VALUE, EXP)
1222              
1223             EXP must be an integer, and VALUE a floating point value. Multiplies
1224             VALUE by two to the power EXP. This gives exact results, except in
1225             cases of underflow and overflow. The range of EXP is not constrained.
1226             All normal floating point multiplication behaviour applies.
1227              
1228             =item copysign(VALUE, SIGN_FROM)
1229              
1230             VALUE and SIGN_FROM must both be floating point values. Returns a
1231             floating point value with the magnitude of VALUE and the sign of
1232             SIGN_FROM. If SIGN_FROM is an unsigned zero then it is treated as
1233             positive. If VALUE is an unsigned zero then it is returned unchanged.
1234             If VALUE is a NaN then it is returned unchanged. If SIGN_FROM is a NaN
1235             then the sign copied to VALUE is unpredictable.
1236              
1237             This is an IEEE 754 standard function. According to the standard NaNs
1238             have a well-behaved sign bit, which can be read and modified by this
1239             function, but Perl only perceives one NaN and can't see its sign bit,
1240             so behaviour on NaNs is not standard-conforming.
1241              
1242             =cut
1243              
1244             sub copysign($$) {
1245             my($val, $signfrom) = @_;
1246             return $val if float_is_nan($val);
1247             $val = -$val if signbit($val) != signbit($signfrom);
1248             return $val;
1249             }
1250              
1251             =item nextup(VALUE)
1252              
1253             VALUE must be a floating point value. Returns the next representable
1254             floating point value adjacent to VALUE with a numerical value that is
1255             strictly greater than VALUE, or returns VALUE unchanged if there is
1256             no such value. Infinite values are regarded as being adjacent to the
1257             largest representable finite values. Zero counts as one value, even if
1258             it is signed, and it is adjacent to the smallest representable positive
1259             and negative finite values. If a zero is returned, because VALUE is
1260             the smallest representable negative value, and zeroes are signed, it is
1261             a negative zero that is returned. Returns NaN if VALUE is a NaN.
1262              
1263             This is an IEEE 754r standard function.
1264              
1265             =cut
1266              
1267             sub nextup($) {
1268             my($val) = @_;
1269             return $val if $val != $val || $val == max_number;
1270             return -(max_finite) if have_infinite && $val == -(max_number);
1271             return min_finite if $val == 0.0;
1272             my($sign, $exp, $significand) = float_parts($val);
1273             if($sign eq "+") {
1274             $significand += significand_step;
1275             if($significand == 2.0) {
1276             return max_number
1277             if have_infinite && $exp == max_finite_exp;
1278             $significand = 1.0;
1279             $exp++;
1280             }
1281             } else {
1282             if($significand == 1.0 && $exp != min_normal_exp) {
1283             $significand = 2.0;
1284             $exp--;
1285             }
1286             $significand -= significand_step;
1287             }
1288             return copysign(mult_pow2($significand, $exp), $val);
1289             }
1290              
1291             =item nextdown(VALUE)
1292              
1293             VALUE must be a floating point value. Returns the next representable
1294             floating point value adjacent to VALUE with a numerical value that
1295             is strictly less than VALUE, or returns VALUE unchanged if there is
1296             no such value. Infinite values are regarded as being adjacent to the
1297             largest representable finite values. Zero counts as one value, even if
1298             it is signed, and it is adjacent to the smallest representable positive
1299             and negative finite values. If a zero is returned, because VALUE is
1300             the smallest representable positive value, and zeroes are signed, it is
1301             a positive zero that is returned. Returns NaN if VALUE is a NaN.
1302              
1303             This is an IEEE 754r standard function.
1304              
1305             =cut
1306              
1307             sub nextdown($) { -nextup(-(my $n = $_[0])) }
1308              
1309             =item nextafter(VALUE, DIRECTION)
1310              
1311             VALUE and DIRECTION must both be floating point values. Returns the
1312             next representable floating point value adjacent to VALUE in the
1313             direction of DIRECTION, or returns DIRECTION if it is numerically
1314             equal to VALUE. Infinite values are regarded as being adjacent to
1315             the largest representable finite values. Zero counts as one value,
1316             even if it is signed, and it is adjacent to the positive and negative
1317             smallest representable finite values. If a zero is returned and zeroes
1318             are signed then it has the same sign as VALUE. Returns NaN if either
1319             argument is a NaN.
1320              
1321             This is an IEEE 754 standard function.
1322              
1323             =cut
1324              
1325             sub nextafter($$) {
1326             my($val, $dir) = @_;
1327             return $_[1] if $dir != $dir || $val == $dir;
1328             return $dir > $val ? nextup($_[0]) : nextdown($_[0]);
1329             }
1330              
1331             =back
1332              
1333             =head1 BUGS
1334              
1335             As of Perl 5.8.7 floating point zeroes will be partially transformed into
1336             integer zeroes if used in almost any arithmetic, including numerical
1337             comparisons. Such a transformed zero appears as a floating point zero
1338             (with its original sign) for some purposes, but behaves as an integer
1339             zero for other purposes. Where this happens to a positive zero the
1340             result is indistinguishable from a true integer zero. Where it happens
1341             to a negative zero the result is a fourth type of zero, the existence of
1342             which is a bug in Perl. This fourth type of zero will give confusing
1343             results, and in particular will elicit inconsistent behaviour from the
1344             functions in this module.
1345              
1346             Because of this transforming behaviour, it is best to avoid relying on
1347             the sign of zeroes. If you require signed-zero semantics then take
1348             special care to maintain signedness. Avoid using a zero directly
1349             in arithmetic and handle it as a special case. Any flavour of zero
1350             can be accurately copied from one scalar to another without affecting
1351             the original. The functions in this module all avoid modifying their
1352             arguments, and where they are meant to return signed zeroes they always
1353             return a pristine one.
1354              
1355             As of Perl 5.8.7 stringification of a floating point zero does not
1356             preserve its signedness. The number-to-string-to-number round trip
1357             turns a positive floating point zero into an integer zero, but accurately
1358             maintains negative and integer zeroes. If a negative zero gets partially
1359             transformed into an integer zero, as described above, the stringification
1360             that it gets is based on its state at the first occasion on which the
1361             scalar was stringified.
1362              
1363             NaN handling is generally not well defined in Perl. Arithmetic with
1364             a mathematically undefined result may either C<die> or generate a NaN.
1365             Avoid relying on any particular behaviour for such operations, even if
1366             your hardware's behaviour is known.
1367              
1368             As of Perl 5.8.7 the B<%> operator truncates its arguments to integers, if
1369             the divisor is within the range of the native integer type. It therefore
1370             operates correctly on non-integer values only when the divisor is
1371             very large.
1372              
1373             =head1 SEE ALSO
1374              
1375             L<Data::Integer>,
1376             L<Scalar::Number>,
1377             L<perlnumber(1)>
1378              
1379             =head1 AUTHOR
1380              
1381             Andrew Main (Zefram) <zefram@fysh.org>
1382              
1383             =head1 COPYRIGHT
1384              
1385             Copyright (C) 2006, 2007, 2008, 2010, 2012, 2017
1386             Andrew Main (Zefram) <zefram@fysh.org>
1387              
1388             =head1 LICENSE
1389              
1390             This module is free software; you can redistribute it and/or modify it
1391             under the same terms as Perl itself.
1392              
1393             =cut
1394              
1395             1;