]> git.lizzy.rs Git - rust.git/blob - src/libstd/num/f64.rs
auto merge of #13711 : alexcrichton/rust/snapshots, r=brson
[rust.git] / src / libstd / num / f64.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Operations and constants for 64-bits floats (`f64` type)
12
13 #![allow(missing_doc)]
14
15 use prelude::*;
16
17 use cast;
18 use default::Default;
19 use from_str::FromStr;
20 use libc::{c_int};
21 use num::{FPCategory, FPNaN, FPInfinite , FPZero, FPSubnormal, FPNormal};
22 use num::{Zero, One, Bounded, strconv};
23 use num;
24 use intrinsics;
25
26 #[allow(dead_code)]
27 mod cmath {
28     use libc::{c_double, c_int};
29
30     #[link_name = "m"]
31     extern {
32         pub fn acos(n: c_double) -> c_double;
33         pub fn asin(n: c_double) -> c_double;
34         pub fn atan(n: c_double) -> c_double;
35         pub fn atan2(a: c_double, b: c_double) -> c_double;
36         pub fn cbrt(n: c_double) -> c_double;
37         pub fn cosh(n: c_double) -> c_double;
38         pub fn erf(n: c_double) -> c_double;
39         pub fn erfc(n: c_double) -> c_double;
40         pub fn expm1(n: c_double) -> c_double;
41         pub fn fdim(a: c_double, b: c_double) -> c_double;
42         pub fn fmax(a: c_double, b: c_double) -> c_double;
43         pub fn fmin(a: c_double, b: c_double) -> c_double;
44         pub fn fmod(a: c_double, b: c_double) -> c_double;
45         pub fn nextafter(x: c_double, y: c_double) -> c_double;
46         pub fn frexp(n: c_double, value: &mut c_int) -> c_double;
47         pub fn hypot(x: c_double, y: c_double) -> c_double;
48         pub fn ldexp(x: c_double, n: c_int) -> c_double;
49         pub fn logb(n: c_double) -> c_double;
50         pub fn log1p(n: c_double) -> c_double;
51         pub fn ilogb(n: c_double) -> c_int;
52         pub fn modf(n: c_double, iptr: &mut c_double) -> c_double;
53         pub fn sinh(n: c_double) -> c_double;
54         pub fn tan(n: c_double) -> c_double;
55         pub fn tanh(n: c_double) -> c_double;
56         pub fn tgamma(n: c_double) -> c_double;
57
58         // These are commonly only available for doubles
59
60         pub fn j0(n: c_double) -> c_double;
61         pub fn j1(n: c_double) -> c_double;
62         pub fn jn(i: c_int, n: c_double) -> c_double;
63
64         pub fn y0(n: c_double) -> c_double;
65         pub fn y1(n: c_double) -> c_double;
66         pub fn yn(i: c_int, n: c_double) -> c_double;
67
68         #[cfg(unix)]
69         pub fn lgamma_r(n: c_double, sign: &mut c_int) -> c_double;
70         #[cfg(windows)]
71         #[link_name="__lgamma_r"]
72         pub fn lgamma_r(n: c_double, sign: &mut c_int) -> c_double;
73     }
74 }
75
76 // FIXME(#11621): These constants should be deprecated once CTFE is implemented
77 // in favour of calling their respective functions in `Bounded` and `Float`.
78
79 pub static RADIX: uint = 2u;
80
81 pub static MANTISSA_DIGITS: uint = 53u;
82 pub static DIGITS: uint = 15u;
83
84 pub static EPSILON: f64 = 2.2204460492503131e-16_f64;
85
86 /// Minimum normalized f64 value
87 pub static MIN_VALUE: f64 = 2.2250738585072014e-308_f64;
88 /// Maximum f64 value
89 pub static MAX_VALUE: f64 = 1.7976931348623157e+308_f64;
90
91 pub static MIN_EXP: int = -1021;
92 pub static MAX_EXP: int = 1024;
93
94 pub static MIN_10_EXP: int = -307;
95 pub static MAX_10_EXP: int = 308;
96
97 pub static NAN: f64 = 0.0_f64/0.0_f64;
98
99 pub static INFINITY: f64 = 1.0_f64/0.0_f64;
100
101 pub static NEG_INFINITY: f64 = -1.0_f64/0.0_f64;
102
103 /// Various useful constants.
104 pub mod consts {
105     // FIXME: replace with mathematical constants from cmath.
106
107     // FIXME(#11621): These constants should be deprecated once CTFE is
108     // implemented in favour of calling their respective functions in `Float`.
109
110     /// Archimedes' constant
111     pub static PI: f64 = 3.14159265358979323846264338327950288_f64;
112
113     /// pi * 2.0
114     pub static PI_2: f64 = 6.28318530717958647692528676655900576_f64;
115
116     /// pi/2.0
117     pub static FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64;
118
119     /// pi/3.0
120     pub static FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64;
121
122     /// pi/4.0
123     pub static FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64;
124
125     /// pi/6.0
126     pub static FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64;
127
128     /// pi/8.0
129     pub static FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64;
130
131     /// 1.0/pi
132     pub static FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64;
133
134     /// 2.0/pi
135     pub static FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64;
136
137     /// 2.0/sqrt(pi)
138     pub static FRAC_2_SQRTPI: f64 = 1.12837916709551257389615890312154517_f64;
139
140     /// sqrt(2.0)
141     pub static SQRT2: f64 = 1.41421356237309504880168872420969808_f64;
142
143     /// 1.0/sqrt(2.0)
144     pub static FRAC_1_SQRT2: f64 = 0.707106781186547524400844362104849039_f64;
145
146     /// Euler's number
147     pub static E: f64 = 2.71828182845904523536028747135266250_f64;
148
149     /// log2(e)
150     pub static LOG2_E: f64 = 1.44269504088896340735992468100189214_f64;
151
152     /// log10(e)
153     pub static LOG10_E: f64 = 0.434294481903251827651128918916605082_f64;
154
155     /// ln(2.0)
156     pub static LN_2: f64 = 0.693147180559945309417232121458176568_f64;
157
158     /// ln(10.0)
159     pub static LN_10: f64 = 2.30258509299404568401799145468436421_f64;
160 }
161
162 impl Num for f64 {}
163
164 #[cfg(not(test))]
165 impl Eq for f64 {
166     #[inline]
167     fn eq(&self, other: &f64) -> bool { (*self) == (*other) }
168 }
169
170 #[cfg(not(test))]
171 impl Ord for f64 {
172     #[inline]
173     fn lt(&self, other: &f64) -> bool { (*self) < (*other) }
174     #[inline]
175     fn le(&self, other: &f64) -> bool { (*self) <= (*other) }
176     #[inline]
177     fn ge(&self, other: &f64) -> bool { (*self) >= (*other) }
178     #[inline]
179     fn gt(&self, other: &f64) -> bool { (*self) > (*other) }
180 }
181
182 impl Default for f64 {
183     #[inline]
184     fn default() -> f64 { 0.0 }
185 }
186
187 impl Zero for f64 {
188     #[inline]
189     fn zero() -> f64 { 0.0 }
190
191     /// Returns true if the number is equal to either `0.0` or `-0.0`
192     #[inline]
193     fn is_zero(&self) -> bool { *self == 0.0 || *self == -0.0 }
194 }
195
196 impl One for f64 {
197     #[inline]
198     fn one() -> f64 { 1.0 }
199 }
200
201 #[cfg(not(test))]
202 impl Add<f64,f64> for f64 {
203     #[inline]
204     fn add(&self, other: &f64) -> f64 { *self + *other }
205 }
206 #[cfg(not(test))]
207 impl Sub<f64,f64> for f64 {
208     #[inline]
209     fn sub(&self, other: &f64) -> f64 { *self - *other }
210 }
211 #[cfg(not(test))]
212 impl Mul<f64,f64> for f64 {
213     #[inline]
214     fn mul(&self, other: &f64) -> f64 { *self * *other }
215 }
216 #[cfg(not(test))]
217 impl Div<f64,f64> for f64 {
218     #[inline]
219     fn div(&self, other: &f64) -> f64 { *self / *other }
220 }
221 #[cfg(not(test))]
222 impl Rem<f64,f64> for f64 {
223     #[inline]
224     fn rem(&self, other: &f64) -> f64 {
225         unsafe { cmath::fmod(*self, *other) }
226     }
227 }
228 #[cfg(not(test))]
229 impl Neg<f64> for f64 {
230     #[inline]
231     fn neg(&self) -> f64 { -*self }
232 }
233
234 impl Signed for f64 {
235     /// Computes the absolute value. Returns `NAN` if the number is `NAN`.
236     #[inline]
237     fn abs(&self) -> f64 {
238         unsafe { intrinsics::fabsf64(*self) }
239     }
240
241     /// The positive difference of two numbers. Returns `0.0` if the number is less than or
242     /// equal to `other`, otherwise the difference between`self` and `other` is returned.
243     #[inline]
244     fn abs_sub(&self, other: &f64) -> f64 {
245         unsafe { cmath::fdim(*self, *other) }
246     }
247
248     /// # Returns
249     ///
250     /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
251     /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
252     /// - `NAN` if the number is NaN
253     #[inline]
254     fn signum(&self) -> f64 {
255         if self.is_nan() { NAN } else {
256             unsafe { intrinsics::copysignf64(1.0, *self) }
257         }
258     }
259
260     /// Returns `true` if the number is positive, including `+0.0` and `INFINITY`
261     #[inline]
262     fn is_positive(&self) -> bool { *self > 0.0 || (1.0 / *self) == INFINITY }
263
264     /// Returns `true` if the number is negative, including `-0.0` and `NEG_INFINITY`
265     #[inline]
266     fn is_negative(&self) -> bool { *self < 0.0 || (1.0 / *self) == NEG_INFINITY }
267 }
268
269 impl Bounded for f64 {
270     // NOTE: this is the smallest non-infinite f32 value, *not* MIN_VALUE
271     #[inline]
272     fn min_value() -> f64 { -MAX_VALUE }
273
274     #[inline]
275     fn max_value() -> f64 { MAX_VALUE }
276 }
277
278 impl Primitive for f64 {}
279
280 impl Float for f64 {
281     #[inline]
282     fn nan() -> f64 { NAN }
283
284     #[inline]
285     fn infinity() -> f64 { INFINITY }
286
287     #[inline]
288     fn neg_infinity() -> f64 { NEG_INFINITY }
289
290     #[inline]
291     fn neg_zero() -> f64 { -0.0 }
292
293     /// Returns `true` if the number is NaN
294     #[inline]
295     fn is_nan(self) -> bool { self != self }
296
297     /// Returns `true` if the number is infinite
298     #[inline]
299     fn is_infinite(self) -> bool {
300         self == Float::infinity() || self == Float::neg_infinity()
301     }
302
303     /// Returns `true` if the number is neither infinite or NaN
304     #[inline]
305     fn is_finite(self) -> bool {
306         !(self.is_nan() || self.is_infinite())
307     }
308
309     /// Returns `true` if the number is neither zero, infinite, subnormal or NaN
310     #[inline]
311     fn is_normal(self) -> bool {
312         self.classify() == FPNormal
313     }
314
315     /// Returns the floating point category of the number. If only one property
316     /// is going to be tested, it is generally faster to use the specific
317     /// predicate instead.
318     fn classify(self) -> FPCategory {
319         static EXP_MASK: u64 = 0x7ff0000000000000;
320         static MAN_MASK: u64 = 0x000fffffffffffff;
321
322         let bits: u64 = unsafe { cast::transmute(self) };
323         match (bits & MAN_MASK, bits & EXP_MASK) {
324             (0, 0)        => FPZero,
325             (_, 0)        => FPSubnormal,
326             (0, EXP_MASK) => FPInfinite,
327             (_, EXP_MASK) => FPNaN,
328             _             => FPNormal,
329         }
330     }
331
332     #[inline]
333     fn mantissa_digits(_: Option<f64>) -> uint { 53 }
334
335     #[inline]
336     fn digits(_: Option<f64>) -> uint { 15 }
337
338     #[inline]
339     fn epsilon() -> f64 { 2.2204460492503131e-16 }
340
341     #[inline]
342     fn min_exp(_: Option<f64>) -> int { -1021 }
343
344     #[inline]
345     fn max_exp(_: Option<f64>) -> int { 1024 }
346
347     #[inline]
348     fn min_10_exp(_: Option<f64>) -> int { -307 }
349
350     #[inline]
351     fn max_10_exp(_: Option<f64>) -> int { 308 }
352
353     /// Constructs a floating point number by multiplying `x` by 2 raised to the
354     /// power of `exp`
355     #[inline]
356     fn ldexp(x: f64, exp: int) -> f64 {
357         unsafe { cmath::ldexp(x, exp as c_int) }
358     }
359
360     /// Breaks the number into a normalized fraction and a base-2 exponent,
361     /// satisfying:
362     ///
363     /// - `self = x * pow(2, exp)`
364     /// - `0.5 <= abs(x) < 1.0`
365     #[inline]
366     fn frexp(self) -> (f64, int) {
367         unsafe {
368             let mut exp = 0;
369             let x = cmath::frexp(self, &mut exp);
370             (x, exp as int)
371         }
372     }
373
374     /// Returns the mantissa, exponent and sign as integers.
375     fn integer_decode(self) -> (u64, i16, i8) {
376         let bits: u64 = unsafe { cast::transmute(self) };
377         let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 };
378         let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16;
379         let mantissa = if exponent == 0 {
380             (bits & 0xfffffffffffff) << 1
381         } else {
382             (bits & 0xfffffffffffff) | 0x10000000000000
383         };
384         // Exponent bias + mantissa shift
385         exponent -= 1023 + 52;
386         (mantissa, exponent, sign)
387     }
388
389     /// Returns the next representable floating-point value in the direction of
390     /// `other`.
391     #[inline]
392     fn next_after(self, other: f64) -> f64 {
393         unsafe { cmath::nextafter(self, other) }
394     }
395
396     /// Round half-way cases toward `NEG_INFINITY`
397     #[inline]
398     fn floor(self) -> f64 {
399         unsafe { intrinsics::floorf64(self) }
400     }
401
402     /// Round half-way cases toward `INFINITY`
403     #[inline]
404     fn ceil(self) -> f64 {
405         unsafe { intrinsics::ceilf64(self) }
406     }
407
408     /// Round half-way cases away from `0.0`
409     #[inline]
410     fn round(self) -> f64 {
411         unsafe { intrinsics::roundf64(self) }
412     }
413
414     /// The integer part of the number (rounds towards `0.0`)
415     #[inline]
416     fn trunc(self) -> f64 {
417         unsafe { intrinsics::truncf64(self) }
418     }
419
420     /// The fractional part of the number, satisfying:
421     ///
422     /// ```rust
423     /// let x = 1.65f64;
424     /// assert!(x == x.trunc() + x.fract())
425     /// ```
426     #[inline]
427     fn fract(self) -> f64 { self - self.trunc() }
428
429     #[inline]
430     fn max(self, other: f64) -> f64 {
431         unsafe { cmath::fmax(self, other) }
432     }
433
434     #[inline]
435     fn min(self, other: f64) -> f64 {
436         unsafe { cmath::fmin(self, other) }
437     }
438
439     /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
440     /// error. This produces a more accurate result with better performance than
441     /// a separate multiplication operation followed by an add.
442     #[inline]
443     fn mul_add(self, a: f64, b: f64) -> f64 {
444         unsafe { intrinsics::fmaf64(self, a, b) }
445     }
446
447     /// The reciprocal (multiplicative inverse) of the number
448     #[inline]
449     fn recip(self) -> f64 { 1.0 / self }
450
451     #[inline]
452     fn powf(self, n: f64) -> f64 {
453         unsafe { intrinsics::powf64(self, n) }
454     }
455
456     #[inline]
457     fn powi(self, n: i32) -> f64 {
458         unsafe { intrinsics::powif64(self, n) }
459     }
460
461     /// sqrt(2.0)
462     #[inline]
463     fn sqrt2() -> f64 { consts::SQRT2 }
464
465     /// 1.0 / sqrt(2.0)
466     #[inline]
467     fn frac_1_sqrt2() -> f64 { consts::FRAC_1_SQRT2 }
468
469     #[inline]
470     fn sqrt(self) -> f64 {
471         unsafe { intrinsics::sqrtf64(self) }
472     }
473
474     #[inline]
475     fn rsqrt(self) -> f64 { self.sqrt().recip() }
476
477     #[inline]
478     fn cbrt(self) -> f64 {
479         unsafe { cmath::cbrt(self) }
480     }
481
482     #[inline]
483     fn hypot(self, other: f64) -> f64 {
484         unsafe { cmath::hypot(self, other) }
485     }
486
487     /// Archimedes' constant
488     #[inline]
489     fn pi() -> f64 { consts::PI }
490
491     /// 2.0 * pi
492     #[inline]
493     fn two_pi() -> f64 { consts::PI_2 }
494
495     /// pi / 2.0
496     #[inline]
497     fn frac_pi_2() -> f64 { consts::FRAC_PI_2 }
498
499     /// pi / 3.0
500     #[inline]
501     fn frac_pi_3() -> f64 { consts::FRAC_PI_3 }
502
503     /// pi / 4.0
504     #[inline]
505     fn frac_pi_4() -> f64 { consts::FRAC_PI_4 }
506
507     /// pi / 6.0
508     #[inline]
509     fn frac_pi_6() -> f64 { consts::FRAC_PI_6 }
510
511     /// pi / 8.0
512     #[inline]
513     fn frac_pi_8() -> f64 { consts::FRAC_PI_8 }
514
515     /// 1.0 / pi
516     #[inline]
517     fn frac_1_pi() -> f64 { consts::FRAC_1_PI }
518
519     /// 2.0 / pi
520     #[inline]
521     fn frac_2_pi() -> f64 { consts::FRAC_2_PI }
522
523     /// 2.0 / sqrt(pi)
524     #[inline]
525     fn frac_2_sqrtpi() -> f64 { consts::FRAC_2_SQRTPI }
526
527     #[inline]
528     fn sin(self) -> f64 {
529         unsafe { intrinsics::sinf64(self) }
530     }
531
532     #[inline]
533     fn cos(self) -> f64 {
534         unsafe { intrinsics::cosf64(self) }
535     }
536
537     #[inline]
538     fn tan(self) -> f64 {
539         unsafe { cmath::tan(self) }
540     }
541
542     #[inline]
543     fn asin(self) -> f64 {
544         unsafe { cmath::asin(self) }
545     }
546
547     #[inline]
548     fn acos(self) -> f64 {
549         unsafe { cmath::acos(self) }
550     }
551
552     #[inline]
553     fn atan(self) -> f64 {
554         unsafe { cmath::atan(self) }
555     }
556
557     #[inline]
558     fn atan2(self, other: f64) -> f64 {
559         unsafe { cmath::atan2(self, other) }
560     }
561
562     /// Simultaneously computes the sine and cosine of the number
563     #[inline]
564     fn sin_cos(self) -> (f64, f64) {
565         (self.sin(), self.cos())
566     }
567
568     /// Euler's number
569     #[inline]
570     fn e() -> f64 { consts::E }
571
572     /// log2(e)
573     #[inline]
574     fn log2_e() -> f64 { consts::LOG2_E }
575
576     /// log10(e)
577     #[inline]
578     fn log10_e() -> f64 { consts::LOG10_E }
579
580     /// ln(2.0)
581     #[inline]
582     fn ln_2() -> f64 { consts::LN_2 }
583
584     /// ln(10.0)
585     #[inline]
586     fn ln_10() -> f64 { consts::LN_10 }
587
588     /// Returns the exponential of the number
589     #[inline]
590     fn exp(self) -> f64 {
591         unsafe { intrinsics::expf64(self) }
592     }
593
594     /// Returns 2 raised to the power of the number
595     #[inline]
596     fn exp2(self) -> f64 {
597         unsafe { intrinsics::exp2f64(self) }
598     }
599
600     /// Returns the exponential of the number, minus `1`, in a way that is
601     /// accurate even if the number is close to zero
602     #[inline]
603     fn exp_m1(self) -> f64 {
604         unsafe { cmath::expm1(self) }
605     }
606
607     /// Returns the natural logarithm of the number
608     #[inline]
609     fn ln(self) -> f64 {
610         unsafe { intrinsics::logf64(self) }
611     }
612
613     /// Returns the logarithm of the number with respect to an arbitrary base
614     #[inline]
615     fn log(self, base: f64) -> f64 { self.ln() / base.ln() }
616
617     /// Returns the base 2 logarithm of the number
618     #[inline]
619     fn log2(self) -> f64 {
620         unsafe { intrinsics::log2f64(self) }
621     }
622
623     /// Returns the base 10 logarithm of the number
624     #[inline]
625     fn log10(self) -> f64 {
626         unsafe { intrinsics::log10f64(self) }
627     }
628
629     /// Returns the natural logarithm of the number plus `1` (`ln(1+n)`) more
630     /// accurately than if the operations were performed separately
631     #[inline]
632     fn ln_1p(self) -> f64 {
633         unsafe { cmath::log1p(self) }
634     }
635
636     #[inline]
637     fn sinh(self) -> f64 {
638         unsafe { cmath::sinh(self) }
639     }
640
641     #[inline]
642     fn cosh(self) -> f64 {
643         unsafe { cmath::cosh(self) }
644     }
645
646     #[inline]
647     fn tanh(self) -> f64 {
648         unsafe { cmath::tanh(self) }
649     }
650
651     /// Inverse hyperbolic sine
652     ///
653     /// # Returns
654     ///
655     /// - on success, the inverse hyperbolic sine of `self` will be returned
656     /// - `self` if `self` is `0.0`, `-0.0`, `INFINITY`, or `NEG_INFINITY`
657     /// - `NAN` if `self` is `NAN`
658     #[inline]
659     fn asinh(self) -> f64 {
660         match self {
661             NEG_INFINITY => NEG_INFINITY,
662             x => (x + ((x * x) + 1.0).sqrt()).ln(),
663         }
664     }
665
666     /// Inverse hyperbolic cosine
667     ///
668     /// # Returns
669     ///
670     /// - on success, the inverse hyperbolic cosine of `self` will be returned
671     /// - `INFINITY` if `self` is `INFINITY`
672     /// - `NAN` if `self` is `NAN` or `self < 1.0` (including `NEG_INFINITY`)
673     #[inline]
674     fn acosh(self) -> f64 {
675         match self {
676             x if x < 1.0 => Float::nan(),
677             x => (x + ((x * x) - 1.0).sqrt()).ln(),
678         }
679     }
680
681     /// Inverse hyperbolic tangent
682     ///
683     /// # Returns
684     ///
685     /// - on success, the inverse hyperbolic tangent of `self` will be returned
686     /// - `self` if `self` is `0.0` or `-0.0`
687     /// - `INFINITY` if `self` is `1.0`
688     /// - `NEG_INFINITY` if `self` is `-1.0`
689     /// - `NAN` if the `self` is `NAN` or outside the domain of `-1.0 <= self <= 1.0`
690     ///   (including `INFINITY` and `NEG_INFINITY`)
691     #[inline]
692     fn atanh(self) -> f64 {
693         0.5 * ((2.0 * self) / (1.0 - self)).ln_1p()
694     }
695
696     /// Converts to degrees, assuming the number is in radians
697     #[inline]
698     fn to_degrees(self) -> f64 { self * (180.0f64 / Float::pi()) }
699
700     /// Converts to radians, assuming the number is in degrees
701     #[inline]
702     fn to_radians(self) -> f64 {
703         let value: f64 = Float::pi();
704         self * (value / 180.0)
705     }
706 }
707
708 //
709 // Section: String Conversions
710 //
711
712 /// Converts a float to a string
713 ///
714 /// # Arguments
715 ///
716 /// * num - The float value
717 #[inline]
718 pub fn to_str(num: f64) -> ~str {
719     let (r, _) = strconv::float_to_str_common(
720         num, 10u, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false);
721     r
722 }
723
724 /// Converts a float to a string in hexadecimal format
725 ///
726 /// # Arguments
727 ///
728 /// * num - The float value
729 #[inline]
730 pub fn to_str_hex(num: f64) -> ~str {
731     let (r, _) = strconv::float_to_str_common(
732         num, 16u, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false);
733     r
734 }
735
736 /// Converts a float to a string in a given radix, and a flag indicating
737 /// whether it's a special value
738 ///
739 /// # Arguments
740 ///
741 /// * num - The float value
742 /// * radix - The base to use
743 #[inline]
744 pub fn to_str_radix_special(num: f64, rdx: uint) -> (~str, bool) {
745     strconv::float_to_str_common(num, rdx, true,
746                            strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false)
747 }
748
749 /// Converts a float to a string with exactly the number of
750 /// provided significant digits
751 ///
752 /// # Arguments
753 ///
754 /// * num - The float value
755 /// * digits - The number of significant digits
756 #[inline]
757 pub fn to_str_exact(num: f64, dig: uint) -> ~str {
758     let (r, _) = strconv::float_to_str_common(
759         num, 10u, true, strconv::SignNeg, strconv::DigExact(dig), strconv::ExpNone, false);
760     r
761 }
762
763 /// Converts a float to a string with a maximum number of
764 /// significant digits
765 ///
766 /// # Arguments
767 ///
768 /// * num - The float value
769 /// * digits - The number of significant digits
770 #[inline]
771 pub fn to_str_digits(num: f64, dig: uint) -> ~str {
772     let (r, _) = strconv::float_to_str_common(
773         num, 10u, true, strconv::SignNeg, strconv::DigMax(dig), strconv::ExpNone, false);
774     r
775 }
776
777 /// Converts a float to a string using the exponential notation with exactly the number of
778 /// provided digits after the decimal point in the significand
779 ///
780 /// # Arguments
781 ///
782 /// * num - The float value
783 /// * digits - The number of digits after the decimal point
784 /// * upper - Use `E` instead of `e` for the exponent sign
785 #[inline]
786 pub fn to_str_exp_exact(num: f64, dig: uint, upper: bool) -> ~str {
787     let (r, _) = strconv::float_to_str_common(
788         num, 10u, true, strconv::SignNeg, strconv::DigExact(dig), strconv::ExpDec, upper);
789     r
790 }
791
792 /// Converts a float to a string using the exponential notation with the maximum number of
793 /// digits after the decimal point in the significand
794 ///
795 /// # Arguments
796 ///
797 /// * num - The float value
798 /// * digits - The number of digits after the decimal point
799 /// * upper - Use `E` instead of `e` for the exponent sign
800 #[inline]
801 pub fn to_str_exp_digits(num: f64, dig: uint, upper: bool) -> ~str {
802     let (r, _) = strconv::float_to_str_common(
803         num, 10u, true, strconv::SignNeg, strconv::DigMax(dig), strconv::ExpDec, upper);
804     r
805 }
806
807 impl num::ToStrRadix for f64 {
808     /// Converts a float to a string in a given radix
809     ///
810     /// # Arguments
811     ///
812     /// * num - The float value
813     /// * radix - The base to use
814     ///
815     /// # Failure
816     ///
817     /// Fails if called on a special value like `inf`, `-inf` or `NAN` due to
818     /// possible misinterpretation of the result at higher bases. If those values
819     /// are expected, use `to_str_radix_special()` instead.
820     #[inline]
821     fn to_str_radix(&self, rdx: uint) -> ~str {
822         let (r, special) = strconv::float_to_str_common(
823             *self, rdx, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false);
824         if special { fail!("number has a special value, \
825                              try to_str_radix_special() if those are expected") }
826         r
827     }
828 }
829
830 /// Convert a string in base 16 to a float.
831 /// Accepts an optional binary exponent.
832 ///
833 /// This function accepts strings such as
834 ///
835 /// * 'a4.fe'
836 /// * '+a4.fe', equivalent to 'a4.fe'
837 /// * '-a4.fe'
838 /// * '2b.aP128', or equivalently, '2b.ap128'
839 /// * '2b.aP-128'
840 /// * '.' (understood as 0)
841 /// * 'c.'
842 /// * '.c', or, equivalently,  '0.c'
843 /// * '+inf', 'inf', '-inf', 'NaN'
844 ///
845 /// Leading and trailing whitespace represent an error.
846 ///
847 /// # Arguments
848 ///
849 /// * num - A string
850 ///
851 /// # Return value
852 ///
853 /// `None` if the string did not represent a valid number.  Otherwise,
854 /// `Some(n)` where `n` is the floating-point number represented by `[num]`.
855 #[inline]
856 pub fn from_str_hex(num: &str) -> Option<f64> {
857     strconv::from_str_common(num, 16u, true, true, true,
858                              strconv::ExpBin, false, false)
859 }
860
861 impl FromStr for f64 {
862     /// Convert a string in base 10 to a float.
863     /// Accepts an optional decimal exponent.
864     ///
865     /// This function accepts strings such as
866     ///
867     /// * '3.14'
868     /// * '+3.14', equivalent to '3.14'
869     /// * '-3.14'
870     /// * '2.5E10', or equivalently, '2.5e10'
871     /// * '2.5E-10'
872     /// * '.' (understood as 0)
873     /// * '5.'
874     /// * '.5', or, equivalently,  '0.5'
875     /// * '+inf', 'inf', '-inf', 'NaN'
876     ///
877     /// Leading and trailing whitespace represent an error.
878     ///
879     /// # Arguments
880     ///
881     /// * num - A string
882     ///
883     /// # Return value
884     ///
885     /// `none` if the string did not represent a valid number.  Otherwise,
886     /// `Some(n)` where `n` is the floating-point number represented by `num`.
887     #[inline]
888     fn from_str(val: &str) -> Option<f64> {
889         strconv::from_str_common(val, 10u, true, true, true,
890                                  strconv::ExpDec, false, false)
891     }
892 }
893
894 impl num::FromStrRadix for f64 {
895     /// Convert a string in a given base to a float.
896     ///
897     /// Due to possible conflicts, this function does **not** accept
898     /// the special values `inf`, `-inf`, `+inf` and `NaN`, **nor**
899     /// does it recognize exponents of any kind.
900     ///
901     /// Leading and trailing whitespace represent an error.
902     ///
903     /// # Arguments
904     ///
905     /// * num - A string
906     /// * radix - The base to use. Must lie in the range [2 .. 36]
907     ///
908     /// # Return value
909     ///
910     /// `None` if the string did not represent a valid number. Otherwise,
911     /// `Some(n)` where `n` is the floating-point number represented by `num`.
912     #[inline]
913     fn from_str_radix(val: &str, rdx: uint) -> Option<f64> {
914         strconv::from_str_common(val, rdx, true, true, false,
915                                  strconv::ExpNone, false, false)
916     }
917 }
918
919 #[cfg(test)]
920 mod tests {
921     use f64::*;
922     use num::*;
923     use num;
924
925     #[test]
926     fn test_min_nan() {
927         assert_eq!(NAN.min(2.0), 2.0);
928         assert_eq!(2.0f64.min(NAN), 2.0);
929     }
930
931     #[test]
932     fn test_max_nan() {
933         assert_eq!(NAN.max(2.0), 2.0);
934         assert_eq!(2.0f64.max(NAN), 2.0);
935     }
936
937     #[test]
938     fn test_num() {
939         num::test_num(10f64, 2f64);
940     }
941
942     #[test]
943     fn test_floor() {
944         assert_approx_eq!(1.0f64.floor(), 1.0f64);
945         assert_approx_eq!(1.3f64.floor(), 1.0f64);
946         assert_approx_eq!(1.5f64.floor(), 1.0f64);
947         assert_approx_eq!(1.7f64.floor(), 1.0f64);
948         assert_approx_eq!(0.0f64.floor(), 0.0f64);
949         assert_approx_eq!((-0.0f64).floor(), -0.0f64);
950         assert_approx_eq!((-1.0f64).floor(), -1.0f64);
951         assert_approx_eq!((-1.3f64).floor(), -2.0f64);
952         assert_approx_eq!((-1.5f64).floor(), -2.0f64);
953         assert_approx_eq!((-1.7f64).floor(), -2.0f64);
954     }
955
956     #[test]
957     fn test_ceil() {
958         assert_approx_eq!(1.0f64.ceil(), 1.0f64);
959         assert_approx_eq!(1.3f64.ceil(), 2.0f64);
960         assert_approx_eq!(1.5f64.ceil(), 2.0f64);
961         assert_approx_eq!(1.7f64.ceil(), 2.0f64);
962         assert_approx_eq!(0.0f64.ceil(), 0.0f64);
963         assert_approx_eq!((-0.0f64).ceil(), -0.0f64);
964         assert_approx_eq!((-1.0f64).ceil(), -1.0f64);
965         assert_approx_eq!((-1.3f64).ceil(), -1.0f64);
966         assert_approx_eq!((-1.5f64).ceil(), -1.0f64);
967         assert_approx_eq!((-1.7f64).ceil(), -1.0f64);
968     }
969
970     #[test]
971     fn test_round() {
972         assert_approx_eq!(1.0f64.round(), 1.0f64);
973         assert_approx_eq!(1.3f64.round(), 1.0f64);
974         assert_approx_eq!(1.5f64.round(), 2.0f64);
975         assert_approx_eq!(1.7f64.round(), 2.0f64);
976         assert_approx_eq!(0.0f64.round(), 0.0f64);
977         assert_approx_eq!((-0.0f64).round(), -0.0f64);
978         assert_approx_eq!((-1.0f64).round(), -1.0f64);
979         assert_approx_eq!((-1.3f64).round(), -1.0f64);
980         assert_approx_eq!((-1.5f64).round(), -2.0f64);
981         assert_approx_eq!((-1.7f64).round(), -2.0f64);
982     }
983
984     #[test]
985     fn test_trunc() {
986         assert_approx_eq!(1.0f64.trunc(), 1.0f64);
987         assert_approx_eq!(1.3f64.trunc(), 1.0f64);
988         assert_approx_eq!(1.5f64.trunc(), 1.0f64);
989         assert_approx_eq!(1.7f64.trunc(), 1.0f64);
990         assert_approx_eq!(0.0f64.trunc(), 0.0f64);
991         assert_approx_eq!((-0.0f64).trunc(), -0.0f64);
992         assert_approx_eq!((-1.0f64).trunc(), -1.0f64);
993         assert_approx_eq!((-1.3f64).trunc(), -1.0f64);
994         assert_approx_eq!((-1.5f64).trunc(), -1.0f64);
995         assert_approx_eq!((-1.7f64).trunc(), -1.0f64);
996     }
997
998     #[test]
999     fn test_fract() {
1000         assert_approx_eq!(1.0f64.fract(), 0.0f64);
1001         assert_approx_eq!(1.3f64.fract(), 0.3f64);
1002         assert_approx_eq!(1.5f64.fract(), 0.5f64);
1003         assert_approx_eq!(1.7f64.fract(), 0.7f64);
1004         assert_approx_eq!(0.0f64.fract(), 0.0f64);
1005         assert_approx_eq!((-0.0f64).fract(), -0.0f64);
1006         assert_approx_eq!((-1.0f64).fract(), -0.0f64);
1007         assert_approx_eq!((-1.3f64).fract(), -0.3f64);
1008         assert_approx_eq!((-1.5f64).fract(), -0.5f64);
1009         assert_approx_eq!((-1.7f64).fract(), -0.7f64);
1010     }
1011
1012     #[test]
1013     fn test_asinh() {
1014         assert_eq!(0.0f64.asinh(), 0.0f64);
1015         assert_eq!((-0.0f64).asinh(), -0.0f64);
1016
1017         let inf: f64 = Float::infinity();
1018         let neg_inf: f64 = Float::neg_infinity();
1019         let nan: f64 = Float::nan();
1020         assert_eq!(inf.asinh(), inf);
1021         assert_eq!(neg_inf.asinh(), neg_inf);
1022         assert!(nan.asinh().is_nan());
1023         assert_approx_eq!(2.0f64.asinh(), 1.443635475178810342493276740273105f64);
1024         assert_approx_eq!((-2.0f64).asinh(), -1.443635475178810342493276740273105f64);
1025     }
1026
1027     #[test]
1028     fn test_acosh() {
1029         assert_eq!(1.0f64.acosh(), 0.0f64);
1030         assert!(0.999f64.acosh().is_nan());
1031
1032         let inf: f64 = Float::infinity();
1033         let neg_inf: f64 = Float::neg_infinity();
1034         let nan: f64 = Float::nan();
1035         assert_eq!(inf.acosh(), inf);
1036         assert!(neg_inf.acosh().is_nan());
1037         assert!(nan.acosh().is_nan());
1038         assert_approx_eq!(2.0f64.acosh(), 1.31695789692481670862504634730796844f64);
1039         assert_approx_eq!(3.0f64.acosh(), 1.76274717403908605046521864995958461f64);
1040     }
1041
1042     #[test]
1043     fn test_atanh() {
1044         assert_eq!(0.0f64.atanh(), 0.0f64);
1045         assert_eq!((-0.0f64).atanh(), -0.0f64);
1046
1047         let inf: f64 = Float::infinity();
1048         let neg_inf: f64 = Float::neg_infinity();
1049         let nan: f64 = Float::nan();
1050         assert_eq!(1.0f64.atanh(), inf);
1051         assert_eq!((-1.0f64).atanh(), neg_inf);
1052         assert!(2f64.atanh().atanh().is_nan());
1053         assert!((-2f64).atanh().atanh().is_nan());
1054         assert!(inf.atanh().is_nan());
1055         assert!(neg_inf.atanh().is_nan());
1056         assert!(nan.atanh().is_nan());
1057         assert_approx_eq!(0.5f64.atanh(), 0.54930614433405484569762261846126285f64);
1058         assert_approx_eq!((-0.5f64).atanh(), -0.54930614433405484569762261846126285f64);
1059     }
1060
1061     #[test]
1062     fn test_real_consts() {
1063         let pi: f64 = Float::pi();
1064         let two_pi: f64 = Float::two_pi();
1065         let frac_pi_2: f64 = Float::frac_pi_2();
1066         let frac_pi_3: f64 = Float::frac_pi_3();
1067         let frac_pi_4: f64 = Float::frac_pi_4();
1068         let frac_pi_6: f64 = Float::frac_pi_6();
1069         let frac_pi_8: f64 = Float::frac_pi_8();
1070         let frac_1_pi: f64 = Float::frac_1_pi();
1071         let frac_2_pi: f64 = Float::frac_2_pi();
1072         let frac_2_sqrtpi: f64 = Float::frac_2_sqrtpi();
1073         let sqrt2: f64 = Float::sqrt2();
1074         let frac_1_sqrt2: f64 = Float::frac_1_sqrt2();
1075         let e: f64 = Float::e();
1076         let log2_e: f64 = Float::log2_e();
1077         let log10_e: f64 = Float::log10_e();
1078         let ln_2: f64 = Float::ln_2();
1079         let ln_10: f64 = Float::ln_10();
1080
1081         assert_approx_eq!(two_pi, 2.0 * pi);
1082         assert_approx_eq!(frac_pi_2, pi / 2f64);
1083         assert_approx_eq!(frac_pi_3, pi / 3f64);
1084         assert_approx_eq!(frac_pi_4, pi / 4f64);
1085         assert_approx_eq!(frac_pi_6, pi / 6f64);
1086         assert_approx_eq!(frac_pi_8, pi / 8f64);
1087         assert_approx_eq!(frac_1_pi, 1f64 / pi);
1088         assert_approx_eq!(frac_2_pi, 2f64 / pi);
1089         assert_approx_eq!(frac_2_sqrtpi, 2f64 / pi.sqrt());
1090         assert_approx_eq!(sqrt2, 2f64.sqrt());
1091         assert_approx_eq!(frac_1_sqrt2, 1f64 / 2f64.sqrt());
1092         assert_approx_eq!(log2_e, e.log2());
1093         assert_approx_eq!(log10_e, e.log10());
1094         assert_approx_eq!(ln_2, 2f64.ln());
1095         assert_approx_eq!(ln_10, 10f64.ln());
1096     }
1097
1098     #[test]
1099     pub fn test_abs() {
1100         assert_eq!(INFINITY.abs(), INFINITY);
1101         assert_eq!(1f64.abs(), 1f64);
1102         assert_eq!(0f64.abs(), 0f64);
1103         assert_eq!((-0f64).abs(), 0f64);
1104         assert_eq!((-1f64).abs(), 1f64);
1105         assert_eq!(NEG_INFINITY.abs(), INFINITY);
1106         assert_eq!((1f64/NEG_INFINITY).abs(), 0f64);
1107         assert!(NAN.abs().is_nan());
1108     }
1109
1110     #[test]
1111     fn test_abs_sub() {
1112         assert_eq!((-1f64).abs_sub(&1f64), 0f64);
1113         assert_eq!(1f64.abs_sub(&1f64), 0f64);
1114         assert_eq!(1f64.abs_sub(&0f64), 1f64);
1115         assert_eq!(1f64.abs_sub(&-1f64), 2f64);
1116         assert_eq!(NEG_INFINITY.abs_sub(&0f64), 0f64);
1117         assert_eq!(INFINITY.abs_sub(&1f64), INFINITY);
1118         assert_eq!(0f64.abs_sub(&NEG_INFINITY), INFINITY);
1119         assert_eq!(0f64.abs_sub(&INFINITY), 0f64);
1120     }
1121
1122     #[test]
1123     fn test_abs_sub_nowin() {
1124         assert!(NAN.abs_sub(&-1f64).is_nan());
1125         assert!(1f64.abs_sub(&NAN).is_nan());
1126     }
1127
1128     #[test]
1129     fn test_signum() {
1130         assert_eq!(INFINITY.signum(), 1f64);
1131         assert_eq!(1f64.signum(), 1f64);
1132         assert_eq!(0f64.signum(), 1f64);
1133         assert_eq!((-0f64).signum(), -1f64);
1134         assert_eq!((-1f64).signum(), -1f64);
1135         assert_eq!(NEG_INFINITY.signum(), -1f64);
1136         assert_eq!((1f64/NEG_INFINITY).signum(), -1f64);
1137         assert!(NAN.signum().is_nan());
1138     }
1139
1140     #[test]
1141     fn test_is_positive() {
1142         assert!(INFINITY.is_positive());
1143         assert!(1f64.is_positive());
1144         assert!(0f64.is_positive());
1145         assert!(!(-0f64).is_positive());
1146         assert!(!(-1f64).is_positive());
1147         assert!(!NEG_INFINITY.is_positive());
1148         assert!(!(1f64/NEG_INFINITY).is_positive());
1149         assert!(!NAN.is_positive());
1150     }
1151
1152     #[test]
1153     fn test_is_negative() {
1154         assert!(!INFINITY.is_negative());
1155         assert!(!1f64.is_negative());
1156         assert!(!0f64.is_negative());
1157         assert!((-0f64).is_negative());
1158         assert!((-1f64).is_negative());
1159         assert!(NEG_INFINITY.is_negative());
1160         assert!((1f64/NEG_INFINITY).is_negative());
1161         assert!(!NAN.is_negative());
1162     }
1163
1164     #[test]
1165     fn test_is_normal() {
1166         let nan: f64 = Float::nan();
1167         let inf: f64 = Float::infinity();
1168         let neg_inf: f64 = Float::neg_infinity();
1169         let zero: f64 = Zero::zero();
1170         let neg_zero: f64 = Float::neg_zero();
1171         assert!(!nan.is_normal());
1172         assert!(!inf.is_normal());
1173         assert!(!neg_inf.is_normal());
1174         assert!(!zero.is_normal());
1175         assert!(!neg_zero.is_normal());
1176         assert!(1f64.is_normal());
1177         assert!(1e-307f64.is_normal());
1178         assert!(!1e-308f64.is_normal());
1179     }
1180
1181     #[test]
1182     fn test_classify() {
1183         let nan: f64 = Float::nan();
1184         let inf: f64 = Float::infinity();
1185         let neg_inf: f64 = Float::neg_infinity();
1186         let zero: f64 = Zero::zero();
1187         let neg_zero: f64 = Float::neg_zero();
1188         assert_eq!(nan.classify(), FPNaN);
1189         assert_eq!(inf.classify(), FPInfinite);
1190         assert_eq!(neg_inf.classify(), FPInfinite);
1191         assert_eq!(zero.classify(), FPZero);
1192         assert_eq!(neg_zero.classify(), FPZero);
1193         assert_eq!(1e-307f64.classify(), FPNormal);
1194         assert_eq!(1e-308f64.classify(), FPSubnormal);
1195     }
1196
1197     #[test]
1198     fn test_ldexp() {
1199         // We have to use from_str until base-2 exponents
1200         // are supported in floating-point literals
1201         let f1: f64 = from_str_hex("1p-123").unwrap();
1202         let f2: f64 = from_str_hex("1p-111").unwrap();
1203         assert_eq!(Float::ldexp(1f64, -123), f1);
1204         assert_eq!(Float::ldexp(1f64, -111), f2);
1205
1206         assert_eq!(Float::ldexp(0f64, -123), 0f64);
1207         assert_eq!(Float::ldexp(-0f64, -123), -0f64);
1208
1209         let inf: f64 = Float::infinity();
1210         let neg_inf: f64 = Float::neg_infinity();
1211         let nan: f64 = Float::nan();
1212         assert_eq!(Float::ldexp(inf, -123), inf);
1213         assert_eq!(Float::ldexp(neg_inf, -123), neg_inf);
1214         assert!(Float::ldexp(nan, -123).is_nan());
1215     }
1216
1217     #[test]
1218     fn test_frexp() {
1219         // We have to use from_str until base-2 exponents
1220         // are supported in floating-point literals
1221         let f1: f64 = from_str_hex("1p-123").unwrap();
1222         let f2: f64 = from_str_hex("1p-111").unwrap();
1223         let (x1, exp1) = f1.frexp();
1224         let (x2, exp2) = f2.frexp();
1225         assert_eq!((x1, exp1), (0.5f64, -122));
1226         assert_eq!((x2, exp2), (0.5f64, -110));
1227         assert_eq!(Float::ldexp(x1, exp1), f1);
1228         assert_eq!(Float::ldexp(x2, exp2), f2);
1229
1230         assert_eq!(0f64.frexp(), (0f64, 0));
1231         assert_eq!((-0f64).frexp(), (-0f64, 0));
1232     }
1233
1234     #[test] #[ignore(cfg(windows))] // FIXME #8755
1235     fn test_frexp_nowin() {
1236         let inf: f64 = Float::infinity();
1237         let neg_inf: f64 = Float::neg_infinity();
1238         let nan: f64 = Float::nan();
1239         assert_eq!(match inf.frexp() { (x, _) => x }, inf)
1240         assert_eq!(match neg_inf.frexp() { (x, _) => x }, neg_inf)
1241         assert!(match nan.frexp() { (x, _) => x.is_nan() })
1242     }
1243
1244     #[test]
1245     fn test_integer_decode() {
1246         assert_eq!(3.14159265359f64.integer_decode(), (7074237752028906u64, -51i16, 1i8));
1247         assert_eq!((-8573.5918555f64).integer_decode(), (4713381968463931u64, -39i16, -1i8));
1248         assert_eq!(2f64.powf(100.0).integer_decode(), (4503599627370496u64, 48i16, 1i8));
1249         assert_eq!(0f64.integer_decode(), (0u64, -1075i16, 1i8));
1250         assert_eq!((-0f64).integer_decode(), (0u64, -1075i16, -1i8));
1251         assert_eq!(INFINITY.integer_decode(), (4503599627370496u64, 972i16, 1i8));
1252         assert_eq!(NEG_INFINITY.integer_decode(), (4503599627370496, 972, -1));
1253         assert_eq!(NAN.integer_decode(), (6755399441055744u64, 972i16, 1i8));
1254     }
1255 }