Macro astro_float::expr
source · expr!() { /* proc-macro */ }
Expand description
Computes an expression with the specified precision and rounding mode.
The macro accepts an expression to compute and a context. In the expression you can specify:
- Path expressions: variable names, constant names, etc.
- Integer literals, e.g.
123
,-5
. - Floating point literals, e.g.
1.234e-567
. - String literals, e.g.
"-1.234_e-567"
. - Binary operators.
- Unary
-
operator. - Mathematical functions.
- Grouping with
(
and)
.
Supported binary operators:
+
: addition.-
: subtraction.*
: multiplication./
: division.%
: modular division.
Supported mathematical functions:
recip(x)
: reciprocal ofx
.sqrt(x)
: square root ofx
.cbrt(x)
: cube root ofx
.ln(x)
: natural logarithm ofx
.log2(x)
: logarithm base 2 ofx
.log10(x)
: logarithm base 10 ofx
.log(x, b)
: logarithm with baseb
ofx
.exp(x)
:e
to the power ofx
.pow(b, x)
:b
to the power ofx
.sin(x)
: sine ofx
.cos(x)
: cosine ofx
.tan(x)
: tangent ofx
.asin(x)
: arcsine ofx
.acos(x)
: arccosine ofx
.atan(x)
: arctangent ofx
.sinh(x)
: hyperbolic sine ofx
.cosh(x)
: hyperbolic cosine ofx
.tanh(x)
: hyperbolic tangent ofx
.asinh(x)
: hyperbolic arcsine ofx
.acosh(x)
: hyperbolic arccosine ofx
.atanh(x)
: hyperbolic arctangent ofx
.
The context determines the precision, the rounding mode of the result, and also contains the cache of constants.
Tuple (usize, RoundingMode, &mut Consts)
can also be used as a temporary context (see example below).
The macro will determine additional precision needed to compensate error and perform correct rounding. It will also try to eliminate cancellation which may appear when expression is computed.
Avoid passing expressions which contain mathematical identity if you expect a correctly rounded result.
Examples of such expressions:
expr!(sin(x) - sin(x), ctx)
expr!(ln(exp(x)), ctx)
,expr!(sin(x) * sin(x) / (1 - cos(x) * cos(x)), ctx)
,
Macro does not analyze the expression for presense of identity and will increase the precision infinitely and will never return.
Although, you can specify rounding mode None
. In this case, macro will return even if you pass an identity expression.
Examples
// Precision, rounding mode, and constants cache.
let p = 128;
let rm = RoundingMode::Up;
let mut cc = Consts::new().expect("Failed to allocate constants cache");
// Create a context.
let mut ctx = Context::new(p, rm, cc);
let x = 123;
let y = "2345";
let z = 234.5e+1;
// Compute an expression.
let ret = expr!(x + y / z - ("120" - 120), &mut ctx);
assert_eq!(ret, BigFloat::from(124));
// Destructure context.
let (p, rm, mut cc) = ctx.to_raw_parts();
// Compute an expression using temporary context.
let ret = expr!(x + y / z, (p, rm, &mut cc));
assert_eq!(ret, BigFloat::from(124));