rune/modules/f64.rs
1//! Floating point numbers.
2
3use core::cmp::Ordering;
4use core::num::ParseFloatError;
5
6use crate as rune;
7use crate::runtime::{VmError, VmErrorKind};
8use crate::{docstring, ContextError, Module};
9
10/// Mathematical constants mirroring Rust's [core::f64::consts].
11pub mod consts {
12 use crate as rune;
13 use crate::{docstring, ContextError, Module};
14
15 /// Mathematical constants mirroring Rust's [core::f64::consts].
16 #[rune::module(::std::f64::consts)]
17 pub fn module() -> Result<Module, ContextError> {
18 let mut m = Module::from_meta(self::module__meta)?;
19
20 m.constant("E", core::f64::consts::E)
21 .build()?
22 .docs(docstring!(
23 /// Euler's number (e)
24 ))?;
25
26 m.constant("FRAC_1_PI", core::f64::consts::FRAC_1_PI)
27 .build()?
28 .docs(docstring!(
29 /// 1 / π
30 ))?;
31 m.constant("FRAC_1_SQRT_2", core::f64::consts::FRAC_1_SQRT_2)
32 .build()?
33 .docs(docstring!(
34 /// 1 / sqrt(2)
35 ))?;
36 m.constant("FRAC_2_PI", core::f64::consts::FRAC_2_PI)
37 .build()?
38 .docs(docstring!(
39 /// 2 / π
40 ))?;
41 m.constant("FRAC_2_SQRT_PI", core::f64::consts::FRAC_2_SQRT_PI)
42 .build()?
43 .docs(docstring!(
44 /// 2 / sqrt(π)
45 ))?;
46
47 m.constant("FRAC_PI_2", core::f64::consts::FRAC_PI_2)
48 .build()?
49 .docs(docstring!(
50 /// π/2
51 ))?;
52 m.constant("FRAC_PI_3", core::f64::consts::FRAC_PI_3)
53 .build()?
54 .docs(docstring!(
55 /// π/3
56 ))?;
57 m.constant("FRAC_PI_4", core::f64::consts::FRAC_PI_4)
58 .build()?
59 .docs(docstring!(
60 /// π/4
61 ))?;
62 m.constant("FRAC_PI_6", core::f64::consts::FRAC_PI_6)
63 .build()?
64 .docs(docstring!(
65 /// π/6
66 ))?;
67 m.constant("FRAC_PI_8", core::f64::consts::FRAC_PI_8)
68 .build()?
69 .docs(docstring!(
70 /// π/8
71 ))?;
72
73 m.constant("LN_2", core::f64::consts::LN_2)
74 .build()?
75 .docs(docstring!(
76 /// ln(2)
77 ))?;
78 m.constant("LN_10", core::f64::consts::LN_10)
79 .build()?
80 .docs(docstring!(
81 /// ln(10)
82 ))?;
83 m.constant("LOG2_10", core::f64::consts::LOG2_10)
84 .build()?
85 .docs(docstring!(
86 /// log<sub>2</sub>(10)
87 ))?;
88 m.constant("LOG2_E", core::f64::consts::LOG2_E)
89 .build()?
90 .docs(docstring!(
91 /// log<sub>2</sub>(e)
92 ))?;
93 m.constant("LOG10_2", core::f64::consts::LOG10_2)
94 .build()?
95 .docs(docstring!(
96 /// log<sub>10</sub>(2)
97 ))?;
98 m.constant("LOG10_E", core::f64::consts::LOG10_E)
99 .build()?
100 .docs(docstring!(
101 /// log<sub>10</sub>(e)
102 ))?;
103
104 m.constant("PI", core::f64::consts::PI)
105 .build()?
106 .docs(docstring!(
107 /// Archimede's constant (π)
108 ))?;
109 m.constant("SQRT_2", core::f64::consts::SQRT_2)
110 .build()?
111 .docs(docstring!(
112 /// sqrt(2)
113 ))?;
114 m.constant("TAU", core::f64::consts::TAU)
115 .build()?
116 .docs(docstring!(
117 /// The full circle constant (τ)
118 ///
119 /// Equal to 2π
120 ))?;
121
122 Ok(m)
123 }
124}
125
126/// Floating point numbers.
127///
128/// This provides methods for computing over and parsing 64-bit floating pointer
129/// numbers.
130#[rune::module(::std::f64)]
131pub fn module() -> Result<Module, ContextError> {
132 let mut m = Module::from_meta(self::module__meta)?;
133
134 m.function_meta(parse)?
135 .deprecated("Use std::string::parse::<f64> instead")?;
136 m.function_meta(is_nan)?;
137 m.function_meta(is_infinite)?;
138 m.function_meta(is_finite)?;
139 m.function_meta(is_subnormal)?;
140 m.function_meta(is_normal)?;
141 m.function_meta(max__meta)?;
142 m.function_meta(min__meta)?;
143
144 #[cfg(feature = "std")]
145 {
146 m.function_meta(abs)?;
147 m.function_meta(acos)?;
148 m.function_meta(asin)?;
149 m.function_meta(atan)?;
150 m.function_meta(atan2)?;
151 m.function_meta(cbrt)?;
152 m.function_meta(ceil)?;
153 m.function_meta(clamp)?;
154 m.function_meta(cos)?;
155 m.function_meta(div_euclid)?;
156 m.function_meta(exp)?;
157 m.function_meta(exp2)?;
158 m.function_meta(floor)?;
159 m.function_meta(ln)?;
160 m.function_meta(log)?;
161 m.function_meta(log10)?;
162 m.function_meta(log2)?;
163 m.function_meta(powf)?;
164 m.function_meta(powi)?;
165 m.function_meta(rem_euclid)?;
166 m.function_meta(round)?;
167 m.function_meta(sin)?;
168 m.function_meta(sqrt)?;
169 m.function_meta(tan)?;
170 }
171 m.function_meta(to_integer)?;
172 m.function_meta(to_degrees)?;
173 m.function_meta(to_radians)?;
174
175 m.function_meta(clone__meta)?;
176 m.implement_trait::<f64>(rune::item!(::std::clone::Clone))?;
177
178 m.function_meta(partial_eq__meta)?;
179 m.implement_trait::<f64>(rune::item!(::std::cmp::PartialEq))?;
180
181 m.function_meta(eq__meta)?;
182 m.implement_trait::<f64>(rune::item!(::std::cmp::Eq))?;
183
184 m.function_meta(partial_cmp__meta)?;
185 m.implement_trait::<f64>(rune::item!(::std::cmp::PartialOrd))?;
186
187 m.function_meta(cmp__meta)?;
188 m.implement_trait::<f64>(rune::item!(::std::cmp::Ord))?;
189
190 m.constant("EPSILON", f64::EPSILON)
191 .build()?
192 .docs(docstring!(
193 /// [Machine epsilon] value for `f64`.
194 ///
195 /// This is the difference between `1.0` and the next larger representable number.
196 ///
197 /// Equal to 2<sup>1 - MANTISSA_DIGITS</sup>.
198 ///
199 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
200 ))?;
201 m.constant("MIN", f64::MIN).build()?.docs(docstring!(
202 /// The smallest finite `f64` value.
203 ///
204 /// Equal to -[`MAX`].
205 ///
206 /// [`MAX`]: f64::MAX
207 ))?;
208 m.constant("MAX", f64::MAX).build()?.docs(docstring!(
209 /// Largest finite `f64` value.
210 ///
211 /// Equal to
212 /// (1 - 2<sup>-MANTISSA_DIGITS</sup>) 2<sup>[`MAX_EXP`]</sup>.
213 ///
214 /// [`MAX_EXP`]: f64::MAX_EXP
215 ))?;
216 m.constant("MIN_POSITIVE", f64::MIN_POSITIVE)
217 .build()?
218 .docs(docstring!(
219 /// Smallest positive normal `f64` value.
220 ///
221 /// Equal to 2<sup>[`MIN_EXP`] - 1</sup>.
222 ///
223 /// [`MIN_EXP`]: f64::MIN_EXP
224 ))?;
225 m.constant("MIN_EXP", f64::MIN_EXP)
226 .build()?
227 .docs(docstring!(
228 /// One greater than the minimum possible *normal* power of 2 exponent
229 /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
230 ///
231 /// This corresponds to the exact minimum possible *normal* power of 2 exponent
232 /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
233 /// In other words, all normal numbers representable by this type are
234 /// greater than or equal to 0.5 × 2<sup><i>MIN_EXP</i></sup>.
235 ))?;
236 m.constant("MAX_EXP", f64::MAX_EXP)
237 .build()?
238 .docs(docstring!(
239 /// One greater than the maximum possible power of 2 exponent
240 /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
241 ///
242 /// This corresponds to the exact maximum possible power of 2 exponent
243 /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
244 /// In other words, all numbers representable by this type are
245 /// strictly less than 2<sup><i>MAX_EXP</i></sup>.
246 ))?;
247 m.constant("MIN_10_EXP", f64::MIN_10_EXP)
248 .build()?
249 .docs(docstring!(
250 /// Minimum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
251 ///
252 /// Equal to ceil(log<sub>10</sub> [`MIN_POSITIVE`]).
253 ///
254 /// [`MIN_POSITIVE`]: f64::MIN_POSITIVE
255 ))?;
256 m.constant("MAX_10_EXP", f64::MAX_10_EXP)
257 .build()?
258 .docs(docstring!(
259 /// Maximum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
260 ///
261 /// Equal to floor(log<sub>10</sub> [`MAX`]).
262 ///
263 /// [`MAX`]: f64::MAX
264 ))?;
265 m.constant("NAN", f64::NAN).build()?.docs(docstring!(
266 /// Not a number (NaN).
267 ///
268 ///
269 /// Note that IEEE 754 doesn't define just a single NaN value; a plethora of bit patterns
270 /// are considered to be NaN. Furthermore, the standard makes a difference between a
271 /// "signaling" and a "quiet" NaN, and allows inspecting its "payload" (the unspecified
272 /// bits in the bit pattern) and its sign. See the [Rust documentation of NaN bit
273 /// patterns](https://doc.rust-lang.org/core/primitive.f32.html#nan-bit-patterns) for more
274 /// info.
275 ///
276 /// This constant is guaranteed to be a quiet NaN (on targets that follow the Rust assumptions
277 /// that the quiet/signaling bit being set to 1 indicates a quiet NaN). Beyond that, nothing is
278 /// guaranteed about the specific bit pattern chosen here: both payload and sign are arbitrary.
279 /// The concrete bit pattern may change across Rust versions and target platforms.
280 ))?;
281 m.constant("INFINITY", f64::INFINITY)
282 .build()?
283 .docs(docstring!(
284 /// Positive infinity (∞).
285 ))?;
286 m.constant("NEG_INFINITY", f64::NEG_INFINITY)
287 .build()?
288 .docs(docstring!(
289 /// Negative infinity (−∞).
290 ))?;
291
292 Ok(m)
293}
294
295#[rune::function]
296fn parse(s: &str) -> Result<f64, ParseFloatError> {
297 str::parse::<f64>(s)
298}
299
300/// Convert a float to a an integer.
301///
302/// # Examples
303///
304/// ```rune
305/// let n = 7.0_f64.to::<i64>();
306/// assert_eq!(n, 7);
307/// ```
308#[rune::function(instance, path = to::<i64>)]
309fn to_integer(value: f64) -> i64 {
310 value as i64
311}
312
313/// Converts radians to degrees.
314///
315/// # Examples
316///
317/// ```rune
318/// let abs_difference = (std::f64::consts::PI.to_degrees() - 180.0).abs();
319/// assert!(abs_difference < 1e-10);
320/// ```
321#[rune::function(instance)]
322fn to_degrees(this: f64) -> f64 {
323 this.to_degrees()
324}
325
326/// Converts degrees to radians.
327///
328/// # Examples
329///
330/// ```rune
331/// let abs_difference = (180.0.to_radians() - std::f64::consts::PI).abs();
332/// assert!(abs_difference < 1e-10);
333/// ```
334#[rune::function(instance)]
335fn to_radians(this: f64) -> f64 {
336 this.to_radians()
337}
338
339/// Returns `true` if this value is NaN.
340///
341/// # Examples
342///
343/// ```rune
344/// let nan = f64::NAN;
345/// let f = 7.0_f64;
346///
347/// assert!(nan.is_nan());
348/// assert!(!f.is_nan());
349/// ```
350#[rune::function(instance)]
351fn is_nan(this: f64) -> bool {
352 this.is_nan()
353}
354
355/// Returns `true` if this value is positive infinity or negative infinity, and
356/// `false` otherwise.
357///
358/// # Examples
359///
360/// ```rune
361/// let f = 7.0f64;
362/// let inf = f64::INFINITY;
363/// let neg_inf = f64::NEG_INFINITY;
364/// let nan = f64::NAN;
365///
366/// assert!(!f.is_infinite());
367/// assert!(!nan.is_infinite());
368///
369/// assert!(inf.is_infinite());
370/// assert!(neg_inf.is_infinite());
371/// ```
372#[rune::function(instance)]
373fn is_infinite(this: f64) -> bool {
374 this.is_infinite()
375}
376
377/// Returns `true` if this number is neither infinite nor NaN.
378///
379/// # Examples
380///
381/// ```rune
382/// let f = 7.0f64;
383/// let inf = f64::INFINITY;
384/// let neg_inf = f64::NEG_INFINITY;
385/// let nan = f64::NAN;
386///
387/// assert!(f.is_finite());
388///
389/// assert!(!nan.is_finite());
390/// assert!(!inf.is_finite());
391/// assert!(!neg_inf.is_finite());
392/// ```
393#[rune::function(instance)]
394fn is_finite(this: f64) -> bool {
395 this.is_finite()
396}
397
398/// Returns `true` if the number is [subnormal].
399///
400/// # Examples
401///
402/// ```rune
403/// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308_f64
404/// let max = f64::MAX;
405/// let lower_than_min = 1.0e-308_f64;
406/// let zero = 0.0_f64;
407///
408/// assert!(!min.is_subnormal());
409/// assert!(!max.is_subnormal());
410///
411/// assert!(!zero.is_subnormal());
412/// assert!(!f64::NAN.is_subnormal());
413/// assert!(!f64::INFINITY.is_subnormal());
414/// // Values between `0` and `min` are Subnormal.
415/// assert!(lower_than_min.is_subnormal());
416/// ```
417///
418/// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
419#[rune::function(instance)]
420fn is_subnormal(this: f64) -> bool {
421 this.is_subnormal()
422}
423
424/// Returns `true` if the number is neither zero, infinite, [subnormal], or NaN.
425///
426/// # Examples
427///
428/// ```rune
429/// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64
430/// let max = f64::MAX;
431/// let lower_than_min = 1.0e-308_f64;
432/// let zero = 0.0f64;
433///
434/// assert!(min.is_normal());
435/// assert!(max.is_normal());
436///
437/// assert!(!zero.is_normal());
438/// assert!(!f64::NAN.is_normal());
439/// assert!(!f64::INFINITY.is_normal());
440/// // Values between `0` and `min` are Subnormal.
441/// assert!(!lower_than_min.is_normal());
442/// ```
443/// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
444#[rune::function(instance)]
445fn is_normal(this: f64) -> bool {
446 this.is_normal()
447}
448
449/// Returns the maximum of the two numbers, ignoring NaN.
450///
451/// If one of the arguments is NaN, then the other argument is returned. This
452/// follows the IEEE 754-2008 semantics for maxNum, except for handling of
453/// signaling NaNs; this function handles all NaNs the same way and avoids
454/// maxNum's problems with associativity. This also matches the behavior of
455/// libm’s fmax.
456///
457/// # Examples
458///
459/// ```rune
460/// let x = 1.0_f64;
461/// let y = 2.0_f64;
462///
463/// assert_eq!(x.max(y), y);
464/// ```
465#[rune::function(keep, instance, protocol = MAX)]
466fn max(this: f64, other: f64) -> f64 {
467 this.max(other)
468}
469
470/// Returns the minimum of the two numbers, ignoring NaN.
471///
472/// If one of the arguments is NaN, then the other argument is returned. This
473/// follows the IEEE 754-2008 semantics for minNum, except for handling of
474/// signaling NaNs; this function handles all NaNs the same way and avoids
475/// minNum's problems with associativity. This also matches the behavior of
476/// libm’s fmin.
477///
478/// # Examples
479///
480/// ```rune
481/// let x = 1.0_f64;
482/// let y = 2.0_f64;
483///
484/// assert_eq!(x.min(y), x);
485/// ```
486#[rune::function(keep, instance, protocol = MIN)]
487fn min(this: f64, other: f64) -> f64 {
488 this.min(other)
489}
490
491/// Returns the square root of a number.
492///
493/// Returns NaN if `self` is a negative number other than `-0.0`.
494///
495/// # Examples
496///
497/// ```rune
498/// let positive = 4.0_f64;
499/// let negative = -4.0_f64;
500/// let negative_zero = -0.0_f64;
501///
502/// let abs_difference = (positive.sqrt() - 2.0).abs();
503///
504/// assert!(abs_difference < 1e-10);
505/// assert!(negative.sqrt().is_nan());
506/// assert!(negative_zero.sqrt() == negative_zero);
507/// ```
508#[rune::function(instance)]
509#[cfg(feature = "std")]
510fn sqrt(this: f64) -> f64 {
511 this.sqrt()
512}
513
514/// Computes the absolute value of `self`.
515///
516/// # Examples
517///
518/// ```rune
519/// let x = 3.5_f64;
520/// let y = -3.5_f64;
521///
522/// let abs_difference_x = (x.abs() - x).abs();
523/// let abs_difference_y = (y.abs() - (-y)).abs();
524///
525/// assert!(abs_difference_x < 1e-10);
526/// assert!(abs_difference_y < 1e-10);
527///
528/// assert!(f64::NAN.abs().is_nan());
529/// ```
530#[rune::function(instance)]
531#[cfg(feature = "std")]
532fn abs(this: f64) -> f64 {
533 this.abs()
534}
535
536/// Raises a number to a floating point power.
537///
538/// # Examples
539///
540/// ```rune
541/// let x = 2.0_f64;
542/// let abs_difference = (x.powf(2.0) - (x * x)).abs();
543///
544/// assert!(abs_difference < 1e-10);
545/// ```
546#[rune::function(instance)]
547#[cfg(feature = "std")]
548fn powf(this: f64, other: f64) -> f64 {
549 this.powf(other)
550}
551
552/// Raises a number to an integer power.
553///
554/// Using this function is generally faster than using `powf`. It might have a
555/// different sequence of rounding operations than `powf`, so the results are
556/// not guaranteed to agree.
557///
558/// # Examples
559///
560/// ```rune
561/// let x = 2.0_f64;
562/// let abs_difference = (x.powi(2) - (x * x)).abs();
563///
564/// assert!(abs_difference < 1e-10);
565/// ```
566#[rune::function(instance)]
567#[cfg(feature = "std")]
568fn powi(this: f64, other: i32) -> f64 {
569 this.powi(other)
570}
571
572/// Returns the largest integer less than or equal to `self`.
573///
574/// # Examples
575///
576/// ```rune
577/// let f = 3.7_f64;
578/// let g = 3.0_f64;
579/// let h = -3.7_f64;
580///
581/// assert!(f.floor() == 3.0);
582/// assert!(g.floor() == 3.0);
583/// assert!(h.floor() == -4.0);
584/// ```
585#[rune::function(instance)]
586#[cfg(feature = "std")]
587fn floor(this: f64) -> f64 {
588 this.floor()
589}
590
591/// Returns the smallest integer greater than or equal to `self`.
592///
593/// # Examples
594///
595/// ```rune
596/// let f = 3.01_f64;
597/// let g = 4.0_f64;
598///
599/// assert_eq!(f.ceil(), 4.0);
600/// assert_eq!(g.ceil(), 4.0);
601/// ```
602#[rune::function(instance)]
603#[cfg(feature = "std")]
604fn ceil(this: f64) -> f64 {
605 this.ceil()
606}
607
608/// Returns the nearest integer to `self`. If a value is half-way between two
609/// integers, round away from `0.0`.
610///
611/// # Examples
612///
613/// ```rune
614/// let f = 3.3_f64;
615/// let g = -3.3_f64;
616/// let h = -3.7_f64;
617/// let i = 3.5_f64;
618/// let j = 4.5_f64;
619///
620/// assert_eq!(f.round(), 3.0);
621/// assert_eq!(g.round(), -3.0);
622/// assert_eq!(h.round(), -4.0);
623/// assert_eq!(i.round(), 4.0);
624/// assert_eq!(j.round(), 5.0);
625/// ```
626#[rune::function(instance)]
627#[cfg(feature = "std")]
628fn round(this: f64) -> f64 {
629 this.round()
630}
631
632/// Clone a `f64`.
633///
634/// Note that since the type is copy, cloning has the same effect as assigning
635/// it.
636///
637/// # Examples
638///
639/// ```rune
640/// let a = 5.0;
641/// let b = a;
642/// let c = a.clone();
643///
644/// a += 1.0;
645///
646/// assert_eq!(a, 6.0);
647/// assert_eq!(b, 5.0);
648/// assert_eq!(c, 5.0);
649/// ```
650#[rune::function(keep, instance, protocol = CLONE)]
651#[inline]
652fn clone(this: f64) -> f64 {
653 this
654}
655
656/// Test two floats for partial equality.
657///
658/// # Examples
659///
660/// ```rune
661/// assert!(5.0 == 5.0);
662/// assert!(5.0 != 10.0);
663/// assert!(10.0 != 5.0);
664/// assert!(10.0 != f64::NAN);
665/// assert!(f64::NAN != f64::NAN);
666/// ```
667#[rune::function(keep, instance, protocol = PARTIAL_EQ)]
668#[inline]
669fn partial_eq(this: f64, rhs: f64) -> bool {
670 this.eq(&rhs)
671}
672
673/// Test two floats for total equality.
674///
675/// # Examples
676///
677/// ```rune
678/// use std::ops::eq;
679///
680/// assert_eq!(eq(5.0, 5.0), true);
681/// assert_eq!(eq(5.0, 10.0), false);
682/// assert_eq!(eq(10.0, 5.0), false);
683/// ```
684#[rune::function(keep, instance, protocol = EQ)]
685#[inline]
686fn eq(this: f64, rhs: f64) -> Result<bool, VmError> {
687 let Some(ordering) = this.partial_cmp(&rhs) else {
688 return Err(VmError::new(VmErrorKind::IllegalFloatComparison {
689 lhs: this,
690 rhs,
691 }));
692 };
693
694 Ok(matches!(ordering, Ordering::Equal))
695}
696
697/// Perform a partial ordered comparison between two floats.
698///
699/// # Examples
700///
701/// ```rune
702/// use std::cmp::Ordering;
703/// use std::ops::partial_cmp;
704///
705/// assert_eq!(partial_cmp(5.0, 10.0), Some(Ordering::Less));
706/// assert_eq!(partial_cmp(10.0, 5.0), Some(Ordering::Greater));
707/// assert_eq!(partial_cmp(5.0, 5.0), Some(Ordering::Equal));
708/// assert_eq!(partial_cmp(5.0, f64::NAN), None);
709/// ```
710#[rune::function(keep, instance, protocol = PARTIAL_CMP)]
711#[inline]
712fn partial_cmp(this: f64, rhs: f64) -> Option<Ordering> {
713 this.partial_cmp(&rhs)
714}
715
716/// Perform a totally ordered comparison between two floats.
717///
718/// # Examples
719///
720/// ```rune
721/// use std::cmp::Ordering;
722/// use std::ops::cmp;
723///
724/// assert_eq!(cmp(5.0, 10.0), Ordering::Less);
725/// assert_eq!(cmp(10.0, 5.0), Ordering::Greater);
726/// assert_eq!(cmp(5.0, 5.0), Ordering::Equal);
727/// ```
728#[rune::function(keep, instance, protocol = CMP)]
729#[inline]
730fn cmp(this: f64, rhs: f64) -> Result<Ordering, VmError> {
731 let Some(ordering) = this.partial_cmp(&rhs) else {
732 return Err(VmError::new(VmErrorKind::IllegalFloatComparison {
733 lhs: this,
734 rhs,
735 }));
736 };
737
738 Ok(ordering)
739}
740
741/// Computes the arccosine of a number.
742///
743/// Return value is in radians in the range [0, pi] or NaN if the number is outside the range [-1,
744/// 1].
745///
746/// # Examples
747///
748/// ```rune
749/// let f = std::f64::consts::FRAC_PI_4;
750///
751/// // acos(cos(pi/4))
752/// let abs_difference = (f.cos().acos() - std::f64::consts::FRAC_PI_4).abs();
753/// assert!(abs_difference < 1e-10);
754/// ```
755#[rune::function(instance)]
756#[cfg(feature = "std")]
757fn acos(this: f64) -> f64 {
758 this.acos()
759}
760
761/// Computes the arcsine of a number.
762///
763/// Return value is in radians in the range [-pi/2, pi/2] or NaN if the number is outside the range
764/// [-1, 1].
765///
766/// # Examples
767///
768/// ```rune
769/// let f = std::f64::consts::FRAC_PI_2;
770///
771/// // asin(sin(pi/2))
772/// let abs_difference = (f.sin().asin() - std::f64::consts::FRAC_PI_2).abs();
773/// assert!(abs_difference < 1e-7);
774/// ```
775#[rune::function(instance)]
776#[cfg(feature = "std")]
777fn asin(this: f64) -> f64 {
778 this.asin()
779}
780
781/// Computes the arctangent of a number.
782///
783/// Return value is in radians in the range [-pi/2, pi/2];
784///
785/// # Examples
786///
787/// ```rune
788/// let f = 1.0;
789///
790/// // atan(tan(1))
791/// let abs_difference = (f.tan().atan() - 1.0).abs();
792/// assert!(abs_difference < 1e-10);
793/// ```
794#[rune::function(instance)]
795#[cfg(feature = "std")]
796fn atan(this: f64) -> f64 {
797 this.atan()
798}
799
800/// Computes the four quadrant arctangent of self (y) and other (x) in radians.
801///
802/// * `x = 0`, `y = 0`: `0`
803/// * `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]`
804/// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]`
805/// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)`
806///
807/// # Examples
808///
809/// ```rune
810/// // Positive angles measured counter-clockwise
811/// // from positive x axis
812/// // -pi/4 radians (45 deg clockwise)
813/// let x1 = 3.0;
814/// let y1 = -3.0;
815///
816/// // 3pi/4 radians (135 deg counter-clockwise)
817/// let x2 = -3.0;
818/// let y2 = 3.0;
819///
820/// let abs_difference_1 = (y1.atan2(x1) - (-std::f64::consts::FRAC_PI_4)).abs();
821/// let abs_difference_2 = (y2.atan2(x2) - (3.0 * std::f64::consts::FRAC_PI_4)).abs();
822///
823/// assert!(abs_difference_1 < 1e-10);
824/// assert!(abs_difference_2 < 1e-10);
825/// ```
826#[rune::function(instance)]
827#[cfg(feature = "std")]
828fn atan2(this: f64, other: f64) -> f64 {
829 this.atan2(other)
830}
831
832/// Returns the cube root of a number.
833///
834/// # Examples
835///
836/// ```rune
837/// let x = 8.0_f64;
838///
839/// // x^(1/3) - 2 == 0
840/// let abs_difference = (x.cbrt() - 2.0).abs();
841/// assert!(abs_difference < 1e-10);
842/// ```
843#[rune::function(instance)]
844#[cfg(feature = "std")]
845fn cbrt(this: f64) -> f64 {
846 this.cbrt()
847}
848
849/// Computes the cosine of a number (in radians).
850///
851/// # Examples
852///
853/// ```rune
854/// let x = 2.0 * std::f64::consts::PI;
855///
856/// let abs_difference = (x.cos() - 1.0).abs();
857/// assert!(abs_difference < 1e-10);
858/// ```
859#[rune::function(instance)]
860#[cfg(feature = "std")]
861fn cos(this: f64) -> f64 {
862 this.cos()
863}
864
865/// Restrict a value to a certain interval unless it is NaN.
866///
867/// Returns `max` if `self` is greater than `max`, and `min` if `self` is less than `min`.
868/// Otherwise this returns `self`.
869///
870/// Note that this function returns NaN if the initial value was NaN as well.
871///
872/// # Panics
873///
874/// Panics if `min > max`, `min` is NaN, or `max` is NaN.
875///
876/// # Examples
877///
878/// ```rune
879/// assert!((-3.0f64).clamp(-2.0, 1.0) == -2.0);
880/// assert!((0.0f64).clamp(-2.0, 1.0) == 0.0);
881/// assert!((2.0f64).clamp(-2.0, 1.0) == 1.0);
882/// assert!((f64::NAN).clamp(-2.0, 1.0).is_nan());
883/// ```
884#[rune::function(instance)]
885#[cfg(feature = "std")]
886fn clamp(this: f64, min: f64, max: f64) -> f64 {
887 this.clamp(min, max)
888}
889
890/// Calculates Euclidean division, the matching method for rem_euclid.
891///
892/// This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`. In other
893/// words, the result is `self / rhs` rounded to the integer `n` such that `self >= n * rhs`.
894///
895/// # Examples
896///
897/// ```rune
898/// let a = 7.0;
899/// let b = 4.0;
900/// assert_eq!(a.div_euclid(b), 1.0); // 7.0 > 4.0 * 1.0
901/// assert_eq!((-a).div_euclid(b), -2.0); // -7.0 >= 4.0 * -2.0
902/// assert_eq!(a.div_euclid(-b), -1.0); // 7.0 >= -4.0 * -1.0
903/// assert_eq!((-a).div_euclid(-b), 2.0); // -7.0 >= -4.0 * 2.0
904/// ```
905#[rune::function(instance)]
906#[cfg(feature = "std")]
907fn div_euclid(this: f64, rhs: f64) -> f64 {
908 this.div_euclid(rhs)
909}
910
911/// Computes the least nonnegative remainder of `self (mod rhs)`.
912///
913/// In particular, the return value `r` satisfies `0.0 <= r < rhs.abs()` in most cases. However,
914/// due to a floating point round-off error it can result in `r == rhs.abs()`, violating the
915/// mathematical definition, if `self` is much smaller than `rhs.abs()` in magnitude and `self <
916/// 0.0`. This result is not an element of the function’s codomain, but it is the closest floating
917/// point number in the real numbers and thus fulfills the property `self == self.div_euclid(rhs) *
918/// rhs + self.rem_euclid(rhs)` approximately.
919///
920/// # Examples
921///
922/// ```rune
923/// let a = 7.0;
924/// let b = 4.0;
925/// assert_eq!(a.rem_euclid(b), 3.0);
926/// assert_eq!((-a).rem_euclid(b), 1.0);
927/// assert_eq!(a.rem_euclid(-b), 3.0);
928/// assert_eq!((-a).rem_euclid(-b), 1.0);
929/// // limitation due to round-off error
930/// assert!((-f64::EPSILON).rem_euclid(3.0) != 0.0);
931/// ```
932#[rune::function(instance)]
933#[cfg(feature = "std")]
934fn rem_euclid(this: f64, rhs: f64) -> f64 {
935 this.rem_euclid(rhs)
936}
937
938/// Returns `e^(self)`, (the exponential function).
939///
940/// # Examples
941///
942/// ```rune
943/// let one = 1.0_f64;
944/// // e^1
945/// let e = one.exp();
946///
947/// // ln(e) - 1 == 0
948/// let abs_difference = (e.ln() - 1.0).abs();
949/// assert!(abs_difference < 1e-10);
950/// ```
951#[rune::function(instance)]
952#[cfg(feature = "std")]
953fn exp(this: f64) -> f64 {
954 this.exp()
955}
956
957/// Returns `2^(self)`.
958///
959/// Examples
960///
961/// ```rune
962/// let f = 2.0_f64;
963///
964/// // 2^2 - 4 == 0
965/// let abs_difference = (f.exp2() - 4.0).abs();
966/// assert!(abs_difference < 1e-10);
967/// ```
968#[rune::function(instance)]
969#[cfg(feature = "std")]
970fn exp2(this: f64) -> f64 {
971 this.exp2()
972}
973
974/// Returns the natural logarithm of the number.
975///
976/// This returns NaN when the number is negative, and negative infinity when number is zero.
977///
978/// # Examples
979///
980/// ```rune
981/// let one = 1.0;
982/// // e^1
983/// let e = one.exp();
984///
985/// // ln(e) - 1 == 0
986/// let abs_difference = (e.ln() - 1.0).abs();
987/// assert!(abs_difference < 1e-10);
988/// ```
989#[rune::function(instance)]
990#[cfg(feature = "std")]
991fn ln(this: f64) -> f64 {
992 this.ln()
993}
994
995/// Returns the logarithm of the number with respect to an arbitrary base.
996///
997/// This returns NaN when the number is negative, and negative infinity when number is zero.
998///
999/// The result might not be correctly rounded owing to implementation details; `self.log2()` can
1000/// produce more accurate results for base 2, and `self.log10()` can produce more accurate results
1001/// for base 10.
1002///
1003/// # Examples
1004///
1005/// ```rune
1006/// let twenty_five = 25.0_f64;
1007///
1008/// // log5(25) - 2 == 0
1009/// let abs_difference = (twenty_five.log(5.0) - 2.0).abs();
1010/// assert!(abs_difference < 1e-10);
1011/// ```
1012#[rune::function(instance)]
1013#[cfg(feature = "std")]
1014fn log(this: f64, base: f64) -> f64 {
1015 this.log(base)
1016}
1017
1018/// Returns the base 2 logarithm of the number.
1019///
1020/// This returns NaN when the number is negative, and negative infinity when number is zero.
1021///
1022/// # Examples
1023///
1024/// ```rune
1025/// let four = 4.0_f64;
1026///
1027/// // log2(4) - 2 == 0
1028/// let abs_difference = (four.log2() - 2.0).abs();
1029///
1030/// assert!(abs_difference < 1e-10);
1031/// ```
1032///
1033/// Non-positive values:
1034///
1035/// ```rune
1036/// assert_eq!(0_f64.log2(), f64::NEG_INFINITY);
1037/// assert!((-42_f64).log2().is_nan());
1038/// ```
1039#[rune::function(instance)]
1040#[cfg(feature = "std")]
1041fn log2(this: f64) -> f64 {
1042 this.log2()
1043}
1044
1045/// Returns the base 10 logarithm of the number.
1046///
1047/// This returns NaN when the number is negative, and negative infinity when number is zero.
1048///
1049/// # Examples
1050///
1051/// ```rune
1052/// let hundred = 100.0_f64;
1053///
1054/// // log10(100) - 2 == 0
1055/// let abs_difference = (hundred.log10() - 2.0).abs();
1056/// assert!(abs_difference < 1e-10);
1057/// ```
1058#[rune::function(instance)]
1059#[cfg(feature = "std")]
1060fn log10(this: f64) -> f64 {
1061 this.log10()
1062}
1063
1064/// Computes the sine of a number (in radians).
1065///
1066/// # Examples
1067///
1068/// ```rune
1069/// let x = std::f64::consts::FRAC_PI_2;
1070///
1071/// let abs_difference = (x.sin() - 1.0).abs();
1072/// assert!(abs_difference < 1e-10);
1073/// ```
1074#[rune::function(instance)]
1075#[cfg(feature = "std")]
1076fn sin(this: f64) -> f64 {
1077 this.sin()
1078}
1079
1080/// Computes the tangent of a number (in radians).
1081///
1082/// # Examples
1083///
1084/// ```rune
1085/// let x = std::f64::consts::FRAC_PI_4;
1086/// let abs_difference = (x.tan() - 1.0).abs();
1087/// assert!(abs_difference < 1e-14);
1088/// ```
1089#[rune::function(instance)]
1090#[cfg(feature = "std")]
1091fn tan(this: f64) -> f64 {
1092 this.tan()
1093}