/
float.rs
579 lines (497 loc) · 16.1 KB
/
float.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// NB: transitionary, de-mode-ing.
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
//! Operations and constants for `float`
// Even though this module exports everything defined in it,
// because it contains re-exports, we also have to explicitly
// export locally defined things. That's a bit annoying.
// export when m_float == c_double
// PORT this must match in width according to architecture
use m_float = f64;
pub use f64::{add, sub, mul, div, rem, lt, le, eq, ne, ge, gt};
pub use f64::logarithm;
pub use f64::{acos, asin, atan2, cbrt, ceil, copysign, cosh, floor};
pub use f64::{erf, erfc, exp, expm1, exp2, abs_sub};
pub use f64::{mul_add, fmax, fmin, nextafter, frexp, hypot, ldexp};
pub use f64::{lgamma, ln, log_radix, ln1p, log10, log2, ilog_radix};
pub use f64::{modf, pow, round, sinh, tanh, tgamma, trunc};
pub use f64::signbit;
pub use f64::{j0, j1, jn, y0, y1, yn};
use cmp::{Eq, Ord};
use num::Num::from_int;
pub const NaN: float = 0.0/0.0;
pub const infinity: float = 1.0/0.0;
pub const neg_infinity: float = -1.0/0.0;
/* Module: consts */
pub mod consts {
// FIXME (requires Issue #1433 to fix): replace with mathematical
// constants from cmath.
/// Archimedes' constant
pub const pi: float = 3.14159265358979323846264338327950288;
/// pi/2.0
pub const frac_pi_2: float = 1.57079632679489661923132169163975144;
/// pi/4.0
pub const frac_pi_4: float = 0.785398163397448309615660845819875721;
/// 1.0/pi
pub const frac_1_pi: float = 0.318309886183790671537767526745028724;
/// 2.0/pi
pub const frac_2_pi: float = 0.636619772367581343075535053490057448;
/// 2.0/sqrt(pi)
pub const frac_2_sqrtpi: float = 1.12837916709551257389615890312154517;
/// sqrt(2.0)
pub const sqrt2: float = 1.41421356237309504880168872420969808;
/// 1.0/sqrt(2.0)
pub const frac_1_sqrt2: float = 0.707106781186547524400844362104849039;
/// Euler's number
pub const e: float = 2.71828182845904523536028747135266250;
/// log2(e)
pub const log2_e: float = 1.44269504088896340735992468100189214;
/// log10(e)
pub const log10_e: float = 0.434294481903251827651128918916605082;
/// ln(2.0)
pub const ln_2: float = 0.693147180559945309417232121458176568;
/// ln(10.0)
pub const ln_10: float = 2.30258509299404568401799145468436421;
}
/**
* Section: String Conversions
*/
/**
* Converts a float to a string
*
* # Arguments
*
* * num - The float value
* * digits - The number of significant digits
* * exact - Whether to enforce the exact number of significant digits
*/
pub pure fn to_str_common(num: float, digits: uint, exact: bool) -> ~str {
if is_NaN(num) { return ~"NaN"; }
if num == infinity { return ~"inf"; }
if num == neg_infinity { return ~"-inf"; }
let mut (num, sign) = if num < 0.0 { (-num, ~"-") } else { (num, ~"") };
// truncated integer
let trunc = num as uint;
// decimal remainder
let mut frac = num - (trunc as float);
// stack of digits
let mut fractionalParts = ~[];
// FIXME: (#2608)
// This used to return right away without rounding, as "~[-]num",
// but given epsilon like in f64.rs, I don't see how the comparison
// to epsilon did much when only used there.
// if (frac < epsilon && !exact) || digits == 0u { return accum; }
//
// With something better, possibly weird results like this can be avoided:
// assert "3.14158999999999988262" == my_to_str_exact(3.14159, 20u);
let mut ii = digits;
let mut epsilon_prime = 1.0 / pow_with_uint(10u, ii);
// while we still need digits
// build stack of digits
while ii > 0 && (frac >= epsilon_prime || exact) {
// store the next digit
frac *= 10.0;
let digit = frac as uint;
// Bleh: not really unsafe.
unsafe { fractionalParts.push(digit); }
// calculate the next frac
frac -= digit as float;
epsilon_prime *= 10.0;
ii -= 1u;
}
let mut acc;
let mut racc = ~"";
let mut carry = if frac * 10.0 as uint >= 5 { 1 } else { 0 };
// turn digits into string
// using stack of digits
while fractionalParts.is_not_empty() {
// Bleh; shouldn't need to be unsafe
let mut adjusted_digit = carry + unsafe { fractionalParts.pop() };
if adjusted_digit == 10 {
carry = 1;
adjusted_digit %= 10
} else {
carry = 0;
};
racc = uint::str(adjusted_digit) + racc;
}
// pad decimals with trailing zeroes
while racc.len() < digits && exact {
racc += ~"0"
}
// combine ints and decimals
let mut ones = uint::str(trunc + carry);
if racc == ~"" {
acc = sign + ones;
} else {
acc = sign + ones + ~"." + racc;
}
move acc
}
/**
* Converts a float to a string with exactly the number of
* provided significant digits
*
* # Arguments
*
* * num - The float value
* * digits - The number of significant digits
*/
pub pure fn to_str_exact(num: float, digits: uint) -> ~str {
to_str_common(num, digits, true)
}
#[test]
pub fn test_to_str_exact_do_decimal() {
let s = to_str_exact(5.0, 4u);
assert s == ~"5.0000";
}
/**
* Converts a float to a string with a maximum number of
* significant digits
*
* # Arguments
*
* * num - The float value
* * digits - The number of significant digits
*/
pub pure fn to_str(num: float, digits: uint) -> ~str {
to_str_common(num, digits, false)
}
/**
* Convert a string to a float
*
* This function accepts strings such as
*
* * '3.14'
* * '+3.14', equivalent to '3.14'
* * '-3.14'
* * '2.5E10', or equivalently, '2.5e10'
* * '2.5E-10'
* * '', or, equivalently, '.' (understood as 0)
* * '5.'
* * '.5', or, equivalently, '0.5'
* * 'inf', '-inf', 'NaN'
*
* Leading and trailing whitespace are ignored.
*
* # Arguments
*
* * num - A string
*
* # Return value
*
* `none` if the string did not represent a valid number. Otherwise,
* `Some(n)` where `n` is the floating-point number represented by `[num]`.
*/
pub pure fn from_str(num: &str) -> Option<float> {
if num == "inf" {
return Some(infinity as float);
} else if num == "-inf" {
return Some(neg_infinity as float);
} else if num == "NaN" {
return Some(NaN as float);
}
let mut pos = 0u; //Current byte position in the string.
//Used to walk the string in O(n).
let len = str::len(num); //Length of the string, in bytes.
if len == 0u { return None; }
let mut total = 0f; //Accumulated result
let mut c = 'z'; //Latest char.
//The string must start with one of the following characters.
match str::char_at(num, 0u) {
'-' | '+' | '0' .. '9' | '.' => (),
_ => return None
}
//Determine if first char is '-'/'+'. Set [pos] and [neg] accordingly.
let mut neg = false; //Sign of the result
match str::char_at(num, 0u) {
'-' => {
neg = true;
pos = 1u;
}
'+' => {
pos = 1u;
}
_ => ()
}
//Examine the following chars until '.', 'e', 'E'
while(pos < len) {
let char_range = str::char_range_at(num, pos);
c = char_range.ch;
pos = char_range.next;
match c {
'0' .. '9' => {
total = total * 10f;
total += ((c as int) - ('0' as int)) as float;
}
'.' | 'e' | 'E' => break,
_ => return None
}
}
if c == '.' {//Examine decimal part
let mut decimal = 1f;
while(pos < len) {
let char_range = str::char_range_at(num, pos);
c = char_range.ch;
pos = char_range.next;
match c {
'0' | '1' | '2' | '3' | '4' | '5' | '6'| '7' | '8' | '9' => {
decimal /= 10f;
total += (((c as int) - ('0' as int)) as float)*decimal;
}
'e' | 'E' => break,
_ => return None
}
}
}
if (c == 'e') || (c == 'E') { //Examine exponent
let mut exponent = 0u;
let mut neg_exponent = false;
if(pos < len) {
let char_range = str::char_range_at(num, pos);
c = char_range.ch;
match c {
'+' => {
pos = char_range.next;
}
'-' => {
pos = char_range.next;
neg_exponent = true;
}
_ => ()
}
while(pos < len) {
let char_range = str::char_range_at(num, pos);
c = char_range.ch;
match c {
'0' | '1' | '2' | '3' | '4' | '5' | '6'| '7' | '8' | '9' => {
exponent *= 10u;
exponent += ((c as uint) - ('0' as uint));
}
_ => break
}
pos = char_range.next;
}
let multiplier = pow_with_uint(10u, exponent);
//Note: not ~[int::pow], otherwise, we'll quickly
//end up with a nice overflow
if neg_exponent {
total = total / multiplier;
} else {
total = total * multiplier;
}
} else {
return None;
}
}
if(pos < len) {
return None;
} else {
if(neg) {
total *= -1f;
}
return Some(total);
}
}
/**
* Section: Arithmetics
*/
/**
* Compute the exponentiation of an integer by another integer as a float
*
* # Arguments
*
* * x - The base
* * pow - The exponent
*
* # Return value
*
* `NaN` if both `x` and `pow` are `0u`, otherwise `x^pow`
*/
pub pure fn pow_with_uint(base: uint, pow: uint) -> float {
if base == 0u {
if pow == 0u {
return NaN as float;
}
return 0.;
}
let mut my_pow = pow;
let mut total = 1f;
let mut multiplier = base as float;
while (my_pow > 0u) {
if my_pow % 2u == 1u {
total = total * multiplier;
}
my_pow /= 2u;
multiplier *= multiplier;
}
return total;
}
pub pure fn is_positive(x: float) -> bool { f64::is_positive(x as f64) }
pub pure fn is_negative(x: float) -> bool { f64::is_negative(x as f64) }
pub pure fn is_nonpositive(x: float) -> bool { f64::is_nonpositive(x as f64) }
pub pure fn is_nonnegative(x: float) -> bool { f64::is_nonnegative(x as f64) }
pub pure fn is_zero(x: float) -> bool { f64::is_zero(x as f64) }
pub pure fn is_infinite(x: float) -> bool { f64::is_infinite(x as f64) }
pub pure fn is_finite(x: float) -> bool { f64::is_finite(x as f64) }
pub pure fn is_NaN(x: float) -> bool { f64::is_NaN(x as f64) }
pub pure fn abs(x: float) -> float { f64::abs(x as f64) as float }
pub pure fn sqrt(x: float) -> float { f64::sqrt(x as f64) as float }
pub pure fn atan(x: float) -> float { f64::atan(x as f64) as float }
pub pure fn sin(x: float) -> float { f64::sin(x as f64) as float }
pub pure fn cos(x: float) -> float { f64::cos(x as f64) as float }
pub pure fn tan(x: float) -> float { f64::tan(x as f64) as float }
#[cfg(notest)]
impl float : Eq {
pure fn eq(&self, other: &float) -> bool { (*self) == (*other) }
pure fn ne(&self, other: &float) -> bool { (*self) != (*other) }
}
#[cfg(notest)]
impl float : Ord {
pure fn lt(&self, other: &float) -> bool { (*self) < (*other) }
pure fn le(&self, other: &float) -> bool { (*self) <= (*other) }
pure fn ge(&self, other: &float) -> bool { (*self) >= (*other) }
pure fn gt(&self, other: &float) -> bool { (*self) > (*other) }
}
impl float: num::Num {
#[inline(always)]
pub pure fn add(&self, other: &float) -> float { return *self + *other; }
#[inline(always)]
pub pure fn sub(&self, other: &float) -> float { return *self - *other; }
#[inline(always)]
pub pure fn mul(&self, other: &float) -> float { return *self * *other; }
#[inline(always)]
pub pure fn div(&self, other: &float) -> float { return *self / *other; }
#[inline(always)]
pure fn modulo(&self, other: &float) -> float { return *self % *other; }
#[inline(always)]
pure fn neg(&self) -> float { return -*self; }
#[inline(always)]
pure fn to_int(&self) -> int { return *self as int; }
#[inline(always)]
static pure fn from_int(&self, n: int) -> float { return n as float; }
}
impl float: num::Zero {
static pure fn zero() -> float { 0.0 }
}
impl float: num::One {
static pure fn one() -> float { 1.0 }
}
#[test]
pub fn test_from_str() {
assert from_str(~"3") == Some(3.);
assert from_str(~"3") == Some(3.);
assert from_str(~"3.14") == Some(3.14);
assert from_str(~"+3.14") == Some(3.14);
assert from_str(~"-3.14") == Some(-3.14);
assert from_str(~"2.5E10") == Some(25000000000.);
assert from_str(~"2.5e10") == Some(25000000000.);
assert from_str(~"25000000000.E-10") == Some(2.5);
assert from_str(~".") == Some(0.);
assert from_str(~".e1") == Some(0.);
assert from_str(~".e-1") == Some(0.);
assert from_str(~"5.") == Some(5.);
assert from_str(~".5") == Some(0.5);
assert from_str(~"0.5") == Some(0.5);
assert from_str(~"0.5") == Some(0.5);
assert from_str(~"0.5") == Some(0.5);
assert from_str(~"-.5") == Some(-0.5);
assert from_str(~"-.5") == Some(-0.5);
assert from_str(~"-5") == Some(-5.);
assert from_str(~"-0") == Some(-0.);
assert from_str(~"0") == Some(0.);
assert from_str(~"inf") == Some(infinity);
assert from_str(~"-inf") == Some(neg_infinity);
// note: NaN != NaN, hence this slightly complex test
match from_str(~"NaN") {
Some(f) => assert is_NaN(f),
None => fail
}
assert from_str(~"").is_none();
assert from_str(~"x").is_none();
assert from_str(~" ").is_none();
assert from_str(~" ").is_none();
assert from_str(~"e").is_none();
assert from_str(~"E").is_none();
assert from_str(~"E1").is_none();
assert from_str(~"1e1e1").is_none();
assert from_str(~"1e1.1").is_none();
assert from_str(~"1e1-1").is_none();
}
#[test]
pub fn test_positive() {
assert(is_positive(infinity));
assert(is_positive(1.));
assert(is_positive(0.));
assert(!is_positive(-1.));
assert(!is_positive(neg_infinity));
assert(!is_positive(1./neg_infinity));
assert(!is_positive(NaN));
}
#[test]
pub fn test_negative() {
assert(!is_negative(infinity));
assert(!is_negative(1.));
assert(!is_negative(0.));
assert(is_negative(-1.));
assert(is_negative(neg_infinity));
assert(is_negative(1./neg_infinity));
assert(!is_negative(NaN));
}
#[test]
pub fn test_nonpositive() {
assert(!is_nonpositive(infinity));
assert(!is_nonpositive(1.));
assert(!is_nonpositive(0.));
assert(is_nonpositive(-1.));
assert(is_nonpositive(neg_infinity));
assert(is_nonpositive(1./neg_infinity));
assert(!is_nonpositive(NaN));
}
#[test]
pub fn test_nonnegative() {
assert(is_nonnegative(infinity));
assert(is_nonnegative(1.));
assert(is_nonnegative(0.));
assert(!is_nonnegative(-1.));
assert(!is_nonnegative(neg_infinity));
assert(!is_nonnegative(1./neg_infinity));
assert(!is_nonnegative(NaN));
}
#[test]
pub fn test_to_str_inf() {
assert to_str(infinity, 10u) == ~"inf";
assert to_str(-infinity, 10u) == ~"-inf";
}
#[test]
pub fn test_traits() {
fn test<U:num::Num cmp::Eq>(ten: &U) {
assert (ten.to_int() == 10);
let two: U = from_int(2);
assert (two.to_int() == 2);
assert (ten.add(&two) == from_int(12));
assert (ten.sub(&two) == from_int(8));
assert (ten.mul(&two) == from_int(20));
assert (ten.div(&two) == from_int(5));
assert (ten.modulo(&two) == from_int(0));
}
test(&10.0);
}
//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
//