nushell/docs/commands/math-eval.md
Shaurya Shubham ffe3e2c16b
Rename calc to math eval and allow it to optionally take an expression as an argument (#2195)
* Rename `calc` to `math eval` and allow it to optionally take the expression as an argument

* Moved calc tests to math eval
Also added 2 tests and changed 1 test

* Move calc docs to math eval
2020-07-18 16:11:19 +12:00

2.8 KiB

math eval

math eval is a command that takes a math expression from the pipeline and evaluates that into a number. It also optionally takes the math expression as an argument.

This command supports the following operations -

operations:

  • binary operators: +, -, *, /, % (remainder), ^ (power)
  • unary operators: +, -, ! (factorial)

functions:

  • sqrt, abs
  • exp, ln, log10
  • sin, cos, tan, asin, acos, atan, atan2
  • sinh, cosh, tanh, asinh, acosh, atanh
  • floor, ceil, round
  • signum
  • max(x, ...), min(x, ...): maximum and minimum of 1 or more numbers

constants:

  • pi
  • e

Examples

> echo "1+2+3" | math eval
6.0u
> echo "1-2+3" | math eval
2.0
> echo "-(-23)" | math eval
23.0
> echo "5^2" | math eval
25.0
> echo "5^3" | math eval
125.0
> echo "min(5,4,3,2,1,0,-100,45)" | math eval
-100.0
> echo "max(5,4,3,2,1,0,-100,45)" | math eval
45.0
> echo sqrt(2) | math eval
1.414213562373095
> echo pi | math eval
3.141592653589793
> echo e | math eval
2.718281828459045
> echo "sin(pi / 2)" | math eval
1.0
> echo "floor(5999/1000)" | math eval
5.0
> open abc.json
───┬──────
 # │ size
───┼──────
 0816
 11627
 21436
 31573
 4935
 552
 6999
 71639
───┴──────
> open abc.json | format "({size} + 500) * 4"
───┬──────────────────
 # │
───┼──────────────────
 0(816 + 500) * 4
 1(1627 + 500) * 4
 2(1436 + 500) * 4
 3(1573 + 500) * 4
 4(935 + 500) * 4
 5(52 + 500) * 4
 6(999 + 500) * 4
 7(1639 + 500) * 4
───┴──────────────────
> open abc.json | format "({size} + 500) * 4" | math eval
───┬───────────
 # │
───┼───────────
 0 │ 5264.0000
 1 │ 8508.0000
 2 │ 7744.0000
 3 │ 8292.0000
 4 │ 5740.0000
 5 │ 2208.0000
 6 │ 5996.0000
 7 │ 8556.0000
───┴───────────
> open abc.json | format "({size} - 1000) * 4" | math eval
───┬────────────
 # │
───┼────────────
 0 │  -736.0000
 1 │  2508.0000
 2 │  1744.0000
 3 │  2292.0000
 4 │  -260.0000
 5 │ -3792.0000
 6 │    -4.0000
 7 │  2556.0000
───┴────────────

Note that since math eval uses floating-point numbers, the result may not always be precise.

> echo "floor(5999999999999999999/1000000000000000000)" | math eval
6.0