2.12. Liczby zespolone

Problem

Chcemy używać w języku Ruby liczb zespolonych i wykonywać na nich operacje arytmetyczne.

Rozwiązanie

Liczby zespolone reprezentowane są w języku Ruby przez klasę Complex. Klasa ta implementuje wszystkie operacje matematyczne i trygonometryczne, jakie zdefiniowane są dla liczb zespolonych.

require 'complex' Complex::I # => Complex(0, 1) a = Complex(1, 4) # => Complex(1, 4) a.real # => 1 #Część rzeczywista a.image # => 4 #Część urojona b = Complex(1.5, 4.25) # => Complex(1.5, 4.25) b + 1.5 # => Complex(3.0, 4.25) b + 1.5*Complex::I # => Complex(1.5, 5.75) a - b # => Complex(-0.5, -0.25) a * b # => Complex(-15.5, 10.25) b.conjugate # => Complex(1.5, -4.25) #Sprzężenie Math::sin(b) # => Complex(34.9720129257216, ...

Get Ruby. Receptury now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.