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