Tuesday, December 8, 2009

Euler's formula in Ruby

require 'mathn'
def euler(prec=10)
  result = Math.exp(Complex(0, -Math::PI))
  "#{result.real.round(prec)}+#{result.imag.round(prec)}i"
end

Let's execute this method with default argument.
> euler
"-1.0+0.0i"
And execute with argument.
> euler 14
"-1.0+-0.0i"
But more precision...
> euler 15
"-1.0+-0.0i"
> euler 16
"-1.0+-1.0e-16i"
It occurs because of floating-point error.

No comments:

Post a Comment