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