How do I do trigonometry and use maths constants in EK9?

← Advanced Type System · Ref: Q1369

The trigonometric and transcendental functions live on Float, and the mathematical constants come from the small stateless Maths type.

CONSTANTS (Maths)

  maths <- Maths()
  piValue <- maths.pi()
  eValue <- maths.e()

FUNCTIONS ON FLOAT (RADIANS)

All trig works in RADIANS:

  sin, cos, tan, asin, acos, atan, atan2
  log (natural), log10, exp

plus sqrt and abs (operators) and ^ (power). For example:

  halfPi <- maths.pi() / 2.0
  s <- halfPi.sin()               // ~ 1.0

UNSET ON OUT-OF-DOMAIN

A result that is not a finite number becomes UNSET rather than a NaN surprise - for example asin of a value outside -1..1, or log of a non-positive value.

ROUNDING

  rounded <- 3.14159.round(2)      // 3.14

Remember to convert degrees to radians yourself (degrees * pi / 180) before calling the trig functions.

See Q23 for the Float type basics. Use 'ek9 -h Float' and 'ek9 -h Maths' for the full API.

Example

defines module qa.maths.usage

  defines program

    MathsUsage()
      stdout <- Stdout()

      maths <- Maths()

      //Trig works in radians: sin(pi/2) ~ 1.0
      halfPi <- maths.pi() / 2.0
      s <- halfPi.sin()
      stdout.println(`sin(pi/2): ${s}`)

      //Natural log of e is 1.0
      lnE <- maths.e().log()
      stdout.println(`ln(e): ${lnE}`)
Other ways to ask this
  • Where are sin, cos, tan in EK9?
  • How do I get pi and e?
  • Does EK9 have log and exp?
  • How do I compute a square root or power?

Coming from another language?

Java: java.lang.Math.sin/cos/... and Math.PI/Math.E. Python: math module (math.sin, math.pi). Go: math package. Rust: f64 methods (x.sin()) and std::f64::consts::PI. EK9: trig/transcendental methods on Float (radians) - sin/cos/tan/asin/acos/atan/atan2/log/log10/exp - plus sqrt/abs/^; constants pi()/e() on the Maths type; out-of-domain results are unset.

Keywords: transcendental, e, sqrt, pi, math, trigonometry, exp, maths, sin, float, cos, radians, tan, log, power