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