Better complex precision

Hi,

Complex numbers use floating point numbers by default. Is there a
way to force them to use BigDecimals (or maybe Rationals) without
creating my own complex class?

THX,
u.

You can use Rational when creation a Complex object:

Complex(Rational(1,3))
=> ((1/3)+0i

2014-07-25 9:16 GMT-03:00 Nokan E. [email protected]:

With Ruby 2.1.2 you can use ‘r’ and ‘i’ to specify rational and
imaginary literals:

[1] pry(main)> RUBY_VERSION
=> “2.1.2”
[2] pry(main)> ans = (1/3r + 2ri) / 3
=> ((1/9)+(2/3)*i)
[3] pry(main)> ans.class
=> Complex
[4] pry(main)> ans.real
=> (1/9)
[5] pry(main)> ans.real.class
=> Rational
[6] pry(main)> ans.imag
=> (2/3)
[7] pry(main)> ans.imag.class
=> Rational

:slight_smile:

Mike

On Jul 25, 2014, at 8:42 AM, Juanjo C. [email protected] wrote:

way to force them to use BigDecimals (or maybe Rationals) without
Juanjo C.
blog: http://www.juanjoconti.com.ar

Mike S. [email protected]
http://www.stok.ca/~mike/

The “`Stok’ disclaimers” apply.

Yes, this is true. But it’s easy to loose this nice behaviour.

2.1.2 :001 > require ‘mathn’
=> true
2.1.2 :002 > z = 1/2ri
=> (0-(1/2)*i)
2.1.2 :003 > z.imag.class
=> Rational
2.1.2 :004 > Math::sin z
=> (0.0-0.5210953054937474i)
2.1.2 :005 > _.imag.class
=> Float :((

What I wanted to ask was if I can force the complex implementation to
always
represent the real and imaginary parts as Rationals or BigDecimals
instead
of
occasionally falling back to Floats.

On Fri, Jul 25, 2014 at 6:10 PM, Nokan E. [email protected]
wrote:

What I wanted to ask was if I can force the complex implementation to always
represent the real and imaginary parts as Rationals or BigDecimals instead
of occasionally falling back to Floats.

One option would be to create your own class for complex numbers.
It’s not that difficult. Open question remains what happens to these
numbers in some library routines. See here for some starting info:
http://blog.rubybestpractices.com/posts/rklemme/019-Complete_Numeric_Class.html

Kind regards

robert