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