Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Complex numbers division error #15072

Open
SlayerShadow opened this issue Oct 9, 2024 · 2 comments
Open

Complex numbers division error #15072

SlayerShadow opened this issue Oct 9, 2024 · 2 comments
Labels
kind:bug A bug in the code. Does not apply to documentation, specs, etc. topic:stdlib:numeric

Comments

@SlayerShadow
Copy link

Guess is complex number math goes wrong in some cases:

require "complex"

c1 = Complex.new 1, 0
c2 = Complex.new -1, 0

p c1 / c2 # => (NaN + NaNi)

(Nani?) :))

Actual result should be (-1 + 0i).

@SlayerShadow SlayerShadow added the kind:bug A bug in the code. Does not apply to documentation, specs, etc. label Oct 9, 2024
@SlayerShadow
Copy link
Author

Translated from npm package:

def /( other : Complex ) : Complex
	if zero? && other.zero? || abs2 == Float64::INFINITY && other.abs2 == Float64::INFINITY
		return Complex.new Float64::NAN, Float64::NAN
	end

	if abs2 == Float64::INFINITY || other.zero?
		return Complex.new Float64::INFINITY, Float64::INFINITY
	end

	if zero? || other.abs2 == Float64::INFINITY
		return Complex.zero
	end

	if other.imag.zero?
		return Complex.new real / other.real, imag / other.real
	end

	if other.real.abs < other.imag.abs
		m = other.real / other.imag
		n = other.real * m + other.imag
		Complex.new ( real * m + imag ) / n, ( imag * m - real ) / n
	else
		m = other.imag / other.real
		n = other.imag * m + other.real
		Complex.new ( real + imag * m ) / n, ( imag - real * m ) / n
	end
end

That works well.

@SlayerShadow
Copy link
Author

At least

if other.real <= other.imag
- this line (if other.real <= other.imag) should include abs for real and image, other logic looks the same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind:bug A bug in the code. Does not apply to documentation, specs, etc. topic:stdlib:numeric
Projects
None yet
Development

No branches or pull requests

2 participants