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