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