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