From 54a5b829442eb7ed1f4a2794ebb26696cf784e64 Mon Sep 17 00:00:00 2001
From: Kenta Murata <3959+mrkn@users.noreply.github.com>
Date: Tue, 27 Feb 2024 09:37:03 +0900
Subject: Handle zero-like imaginary part as zero in to_r (#9581)
Fixes [Bug #5179]
---
complex.c | 16 ++++++++++++----
1 file changed, 12 insertions(+), 4 deletions(-)
(limited to 'complex.c')
diff --git a/complex.c b/complex.c
index 8c32c60523..92245bc9e8 100644
--- a/complex.c
+++ b/complex.c
@@ -1841,9 +1841,11 @@ nucomp_to_f(VALUE self)
*
* Complex.rect(1, 0).to_r # => (1/1)
* Complex.rect(1, Rational(0, 1)).to_r # => (1/1)
+ * Complex.rect(1, 0.0).to_r # => (1/1)
*
* Raises RangeError if self.imag is not exactly zero
- * (either Integer(0) or Rational(0, _n_)).
+ * (either Integer(0) or Rational(0, _n_))
+ * and self.imag.to_r is not exactly zero.
*
* Related: Complex#rationalize.
*/
@@ -1852,9 +1854,15 @@ nucomp_to_r(VALUE self)
{
get_dat1(self);
- if (!k_exact_zero_p(dat->imag)) {
- rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Rational",
- self);
+ if (RB_FLOAT_TYPE_P(dat->imag) && FLOAT_ZERO_P(dat->imag)) {
+ /* Do nothing here */
+ }
+ else if (!k_exact_zero_p(dat->imag)) {
+ VALUE imag = rb_check_convert_type_with_id(dat->imag, T_RATIONAL, "Rational", idTo_r);
+ if (NIL_P(imag) || !k_exact_zero_p(imag)) {
+ rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Rational",
+ self);
+ }
}
return f_to_r(dat->real);
}
--
cgit v1.2.3