1 /*
2   complex.c: Coded by Tadayoshi Funaba 2008-2012
3 
4   This implementation is based on Keiju Ishitsuka's Complex library
5   which is written in ruby.
6 */
7 
8 #include "ruby/config.h"
9 #if defined _MSC_VER
10 /* Microsoft Visual C does not define M_PI and others by default */
11 # define _USE_MATH_DEFINES 1
12 #endif
13 #include <math.h>
14 #include "internal.h"
15 #include "id.h"
16 
17 #define NDEBUG
18 #include "ruby_assert.h"
19 
20 #define ZERO INT2FIX(0)
21 #define ONE INT2FIX(1)
22 #define TWO INT2FIX(2)
23 #if USE_FLONUM
24 #define RFLOAT_0 DBL2NUM(0)
25 #else
26 static VALUE RFLOAT_0;
27 #endif
28 #if defined(HAVE_SIGNBIT) && defined(__GNUC__) && defined(__sun) && \
29     !defined(signbit)
30 extern int signbit(double);
31 #endif
32 
33 VALUE rb_cComplex;
34 
35 static ID id_abs, id_arg,
36     id_denominator, id_fdiv, id_numerator, id_quo,
37     id_real_p, id_i_real, id_i_imag,
38     id_finite_p, id_infinite_p, id_rationalize,
39     id_PI;
40 #define id_to_i idTo_i
41 #define id_to_r idTo_r
42 #define id_negate idUMinus
43 #define id_expt idPow
44 #define id_to_f idTo_f
45 
46 #define f_boolcast(x) ((x) ? Qtrue : Qfalse)
47 
48 #define binop(n,op) \
49 inline static VALUE \
50 f_##n(VALUE x, VALUE y)\
51 {\
52     return rb_funcall(x, (op), 1, y);\
53 }
54 
55 #define fun1(n) \
56 inline static VALUE \
57 f_##n(VALUE x)\
58 {\
59     return rb_funcall(x, id_##n, 0);\
60 }
61 
62 #define fun2(n) \
63 inline static VALUE \
64 f_##n(VALUE x, VALUE y)\
65 {\
66     return rb_funcall(x, id_##n, 1, y);\
67 }
68 
69 #define PRESERVE_SIGNEDZERO
70 
71 inline static VALUE
f_add(VALUE x,VALUE y)72 f_add(VALUE x, VALUE y)
73 {
74     if (RB_INTEGER_TYPE_P(x) &&
75         LIKELY(rb_method_basic_definition_p(rb_cInteger, idPLUS))) {
76         if (FIXNUM_ZERO_P(x))
77             return y;
78         if (FIXNUM_ZERO_P(y))
79             return x;
80         return rb_int_plus(x, y);
81     }
82     else if (RB_FLOAT_TYPE_P(x) &&
83              LIKELY(rb_method_basic_definition_p(rb_cFloat, idPLUS))) {
84         if (FIXNUM_ZERO_P(y))
85             return x;
86         return rb_float_plus(x, y);
87     }
88     else if (RB_TYPE_P(x, T_RATIONAL) &&
89              LIKELY(rb_method_basic_definition_p(rb_cRational, idPLUS))) {
90         if (FIXNUM_ZERO_P(y))
91             return x;
92         return rb_rational_plus(x, y);
93     }
94 
95     return rb_funcall(x, '+', 1, y);
96 }
97 
98 inline static VALUE
f_div(VALUE x,VALUE y)99 f_div(VALUE x, VALUE y)
100 {
101     if (FIXNUM_P(y) && FIX2LONG(y) == 1)
102 	return x;
103     return rb_funcall(x, '/', 1, y);
104 }
105 
106 inline static int
f_gt_p(VALUE x,VALUE y)107 f_gt_p(VALUE x, VALUE y)
108 {
109     if (RB_INTEGER_TYPE_P(x)) {
110         if (FIXNUM_P(x) && FIXNUM_P(y))
111             return (SIGNED_VALUE)x > (SIGNED_VALUE)y;
112         return RTEST(rb_int_gt(x, y));
113     }
114     else if (RB_FLOAT_TYPE_P(x))
115         return RTEST(rb_float_gt(x, y));
116     else if (RB_TYPE_P(x, T_RATIONAL)) {
117         int const cmp = rb_cmpint(rb_rational_cmp(x, y), x, y);
118         return cmp > 0;
119     }
120     return RTEST(rb_funcall(x, '>', 1, y));
121 }
122 
123 inline static VALUE
f_mul(VALUE x,VALUE y)124 f_mul(VALUE x, VALUE y)
125 {
126     if (RB_INTEGER_TYPE_P(x) &&
127         LIKELY(rb_method_basic_definition_p(rb_cInteger, idMULT))) {
128         if (FIXNUM_ZERO_P(y))
129             return ZERO;
130         if (FIXNUM_ZERO_P(x) && RB_INTEGER_TYPE_P(y))
131             return ZERO;
132         if (x == ONE) return y;
133         if (y == ONE) return x;
134         return rb_int_mul(x, y);
135     }
136     else if (RB_FLOAT_TYPE_P(x) &&
137              LIKELY(rb_method_basic_definition_p(rb_cFloat, idMULT))) {
138         if (y == ONE) return x;
139         return rb_float_mul(x, y);
140     }
141     else if (RB_TYPE_P(x, T_RATIONAL) &&
142              LIKELY(rb_method_basic_definition_p(rb_cRational, idMULT))) {
143         if (y == ONE) return x;
144         return rb_rational_mul(x, y);
145     }
146     else if (LIKELY(rb_method_basic_definition_p(CLASS_OF(x), idMULT))) {
147         if (y == ONE) return x;
148     }
149     return rb_funcall(x, '*', 1, y);
150 }
151 
152 inline static VALUE
f_sub(VALUE x,VALUE y)153 f_sub(VALUE x, VALUE y)
154 {
155     if (FIXNUM_ZERO_P(y) &&
156         LIKELY(rb_method_basic_definition_p(CLASS_OF(x), idMINUS))) {
157 	return x;
158     }
159     return rb_funcall(x, '-', 1, y);
160 }
161 
162 fun1(abs)
fun1(arg)163 fun1(arg)
164 fun1(denominator)
165 
166 inline static VALUE
167 f_negate(VALUE x)
168 {
169     if (RB_INTEGER_TYPE_P(x)) {
170         return rb_int_uminus(x);
171     }
172     else if (RB_FLOAT_TYPE_P(x)) {
173         return rb_float_uminus(x);
174     }
175     else if (RB_TYPE_P(x, T_RATIONAL)) {
176         return rb_rational_uminus(x);
177     }
178     else if (RB_TYPE_P(x, T_COMPLEX)) {
179         return rb_complex_uminus(x);
180     }
181     return rb_funcall(x, id_negate, 0);
182 }
183 
184 fun1(numerator)
fun1(real_p)185 fun1(real_p)
186 
187 inline static VALUE
188 f_to_i(VALUE x)
189 {
190     if (RB_TYPE_P(x, T_STRING))
191 	return rb_str_to_inum(x, 10, 0);
192     return rb_funcall(x, id_to_i, 0);
193 }
194 inline static VALUE
f_to_f(VALUE x)195 f_to_f(VALUE x)
196 {
197     if (RB_TYPE_P(x, T_STRING))
198 	return DBL2NUM(rb_str_to_dbl(x, 0));
199     return rb_funcall(x, id_to_f, 0);
200 }
201 
fun1(to_r)202 fun1(to_r)
203 
204 inline static int
205 f_eqeq_p(VALUE x, VALUE y)
206 {
207     if (FIXNUM_P(x) && FIXNUM_P(y))
208 	return x == y;
209     else if (RB_FLOAT_TYPE_P(x) || RB_FLOAT_TYPE_P(y))
210 	return NUM2DBL(x) == NUM2DBL(y);
211     return (int)rb_equal(x, y);
212 }
213 
214 fun2(expt)
fun2(fdiv)215 fun2(fdiv)
216 fun2(quo)
217 
218 inline static int
219 f_negative_p(VALUE x)
220 {
221     if (RB_INTEGER_TYPE_P(x))
222         return INT_NEGATIVE_P(x);
223     else if (RB_FLOAT_TYPE_P(x))
224         return RFLOAT_VALUE(x) < 0.0;
225     else if (RB_TYPE_P(x, T_RATIONAL))
226         return INT_NEGATIVE_P(RRATIONAL(x)->num);
227     return rb_num_negative_p(x);
228 }
229 
230 #define f_positive_p(x) (!f_negative_p(x))
231 
232 inline static int
f_zero_p(VALUE x)233 f_zero_p(VALUE x)
234 {
235     if (RB_INTEGER_TYPE_P(x)) {
236         return FIXNUM_ZERO_P(x);
237     }
238     else if (RB_TYPE_P(x, T_RATIONAL)) {
239         const VALUE num = RRATIONAL(x)->num;
240         return FIXNUM_ZERO_P(num);
241     }
242     return (int)rb_equal(x, ZERO);
243 }
244 
245 #define f_nonzero_p(x) (!f_zero_p(x))
246 
247 VALUE rb_flo_is_finite_p(VALUE num);
248 inline static int
f_finite_p(VALUE x)249 f_finite_p(VALUE x)
250 {
251     if (RB_INTEGER_TYPE_P(x)) {
252         return TRUE;
253     }
254     else if (RB_FLOAT_TYPE_P(x)) {
255 	return (int)rb_flo_is_finite_p(x);
256     }
257     else if (RB_TYPE_P(x, T_RATIONAL)) {
258 	return TRUE;
259     }
260     return RTEST(rb_funcallv(x, id_finite_p, 0, 0));
261 }
262 
263 VALUE rb_flo_is_infinite_p(VALUE num);
264 inline static VALUE
f_infinite_p(VALUE x)265 f_infinite_p(VALUE x)
266 {
267     if (RB_INTEGER_TYPE_P(x)) {
268         return Qnil;
269     }
270     else if (RB_FLOAT_TYPE_P(x)) {
271 	return rb_flo_is_infinite_p(x);
272     }
273     else if (RB_TYPE_P(x, T_RATIONAL)) {
274         return Qnil;
275     }
276     return rb_funcallv(x, id_infinite_p, 0, 0);
277 }
278 
279 inline static int
f_kind_of_p(VALUE x,VALUE c)280 f_kind_of_p(VALUE x, VALUE c)
281 {
282     return (int)rb_obj_is_kind_of(x, c);
283 }
284 
285 inline static int
k_numeric_p(VALUE x)286 k_numeric_p(VALUE x)
287 {
288     return f_kind_of_p(x, rb_cNumeric);
289 }
290 
291 #define k_exact_p(x) (!RB_FLOAT_TYPE_P(x))
292 
293 #define k_exact_zero_p(x) (k_exact_p(x) && f_zero_p(x))
294 
295 #define get_dat1(x) \
296     struct RComplex *dat = RCOMPLEX(x)
297 
298 #define get_dat2(x,y) \
299     struct RComplex *adat = RCOMPLEX(x), *bdat = RCOMPLEX(y)
300 
301 inline static VALUE
nucomp_s_new_internal(VALUE klass,VALUE real,VALUE imag)302 nucomp_s_new_internal(VALUE klass, VALUE real, VALUE imag)
303 {
304     NEWOBJ_OF(obj, struct RComplex, klass, T_COMPLEX | (RGENGC_WB_PROTECTED_COMPLEX ? FL_WB_PROTECTED : 0));
305 
306     RCOMPLEX_SET_REAL(obj, real);
307     RCOMPLEX_SET_IMAG(obj, imag);
308     OBJ_FREEZE_RAW(obj);
309 
310     return (VALUE)obj;
311 }
312 
313 static VALUE
nucomp_s_alloc(VALUE klass)314 nucomp_s_alloc(VALUE klass)
315 {
316     return nucomp_s_new_internal(klass, ZERO, ZERO);
317 }
318 
319 inline static VALUE
f_complex_new_bang1(VALUE klass,VALUE x)320 f_complex_new_bang1(VALUE klass, VALUE x)
321 {
322     assert(!RB_TYPE_P(x, T_COMPLEX));
323     return nucomp_s_new_internal(klass, x, ZERO);
324 }
325 
326 inline static VALUE
f_complex_new_bang2(VALUE klass,VALUE x,VALUE y)327 f_complex_new_bang2(VALUE klass, VALUE x, VALUE y)
328 {
329     assert(!RB_TYPE_P(x, T_COMPLEX));
330     assert(!RB_TYPE_P(y, T_COMPLEX));
331     return nucomp_s_new_internal(klass, x, y);
332 }
333 
334 #ifdef CANONICALIZATION_FOR_MATHN
335 static int canonicalization = 0;
336 
337 RUBY_FUNC_EXPORTED void
nucomp_canonicalization(int f)338 nucomp_canonicalization(int f)
339 {
340     canonicalization = f;
341 }
342 #else
343 #define canonicalization 0
344 #endif
345 
346 inline static void
nucomp_real_check(VALUE num)347 nucomp_real_check(VALUE num)
348 {
349     if (!RB_INTEGER_TYPE_P(num) &&
350 	!RB_FLOAT_TYPE_P(num) &&
351 	!RB_TYPE_P(num, T_RATIONAL)) {
352 	if (!k_numeric_p(num) || !f_real_p(num))
353 	    rb_raise(rb_eTypeError, "not a real");
354     }
355 }
356 
357 inline static VALUE
nucomp_s_canonicalize_internal(VALUE klass,VALUE real,VALUE imag)358 nucomp_s_canonicalize_internal(VALUE klass, VALUE real, VALUE imag)
359 {
360     int complex_r, complex_i;
361 #ifdef CANONICALIZATION_FOR_MATHN
362     if (k_exact_zero_p(imag) && canonicalization)
363 	return real;
364 #endif
365     complex_r = RB_TYPE_P(real, T_COMPLEX);
366     complex_i = RB_TYPE_P(imag, T_COMPLEX);
367     if (!complex_r && !complex_i) {
368 	return nucomp_s_new_internal(klass, real, imag);
369     }
370     else if (!complex_r) {
371 	get_dat1(imag);
372 
373 	return nucomp_s_new_internal(klass,
374 				     f_sub(real, dat->imag),
375 				     f_add(ZERO, dat->real));
376     }
377     else if (!complex_i) {
378 	get_dat1(real);
379 
380 	return nucomp_s_new_internal(klass,
381 				     dat->real,
382 				     f_add(dat->imag, imag));
383     }
384     else {
385 	get_dat2(real, imag);
386 
387 	return nucomp_s_new_internal(klass,
388 				     f_sub(adat->real, bdat->imag),
389 				     f_add(adat->imag, bdat->real));
390     }
391 }
392 
393 /*
394  * call-seq:
395  *    Complex.rect(real[, imag])         ->  complex
396  *    Complex.rectangular(real[, imag])  ->  complex
397  *
398  * Returns a complex object which denotes the given rectangular form.
399  *
400  *    Complex.rectangular(1, 2)  #=> (1+2i)
401  */
402 static VALUE
nucomp_s_new(int argc,VALUE * argv,VALUE klass)403 nucomp_s_new(int argc, VALUE *argv, VALUE klass)
404 {
405     VALUE real, imag;
406 
407     switch (rb_scan_args(argc, argv, "11", &real, &imag)) {
408       case 1:
409 	nucomp_real_check(real);
410 	imag = ZERO;
411 	break;
412       default:
413 	nucomp_real_check(real);
414 	nucomp_real_check(imag);
415 	break;
416     }
417 
418     return nucomp_s_canonicalize_internal(klass, real, imag);
419 }
420 
421 inline static VALUE
f_complex_new2(VALUE klass,VALUE x,VALUE y)422 f_complex_new2(VALUE klass, VALUE x, VALUE y)
423 {
424     assert(!RB_TYPE_P(x, T_COMPLEX));
425     return nucomp_s_canonicalize_internal(klass, x, y);
426 }
427 
428 static VALUE nucomp_convert(VALUE klass, VALUE a1, VALUE a2, int raise);
429 static VALUE nucomp_s_convert(int argc, VALUE *argv, VALUE klass);
430 
431 /*
432  * call-seq:
433  *    Complex(x[, y], exception: false)  ->  numeric
434  *
435  * Returns x+i*y;
436  *
437  *    Complex(1, 2)    #=> (1+2i)
438  *    Complex('1+2i')  #=> (1+2i)
439  *    Complex(nil)     #=> TypeError
440  *    Complex(1, nil)  #=> TypeError
441  *
442  *    Complex(1, nil, exception: false)  #=> nil
443  *    Complex('1+2', exception: false)   #=> nil
444  *
445  * Syntax of string form:
446  *
447  *   string form = extra spaces , complex , extra spaces ;
448  *   complex = real part | [ sign ] , imaginary part
449  *           | real part , sign , imaginary part
450  *           | rational , "@" , rational ;
451  *   real part = rational ;
452  *   imaginary part = imaginary unit | unsigned rational , imaginary unit ;
453  *   rational = [ sign ] , unsigned rational ;
454  *   unsigned rational = numerator | numerator , "/" , denominator ;
455  *   numerator = integer part | fractional part | integer part , fractional part ;
456  *   denominator = digits ;
457  *   integer part = digits ;
458  *   fractional part = "." , digits , [ ( "e" | "E" ) , [ sign ] , digits ] ;
459  *   imaginary unit = "i" | "I" | "j" | "J" ;
460  *   sign = "-" | "+" ;
461  *   digits = digit , { digit | "_" , digit };
462  *   digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
463  *   extra spaces = ? \s* ? ;
464  *
465  * See String#to_c.
466  */
467 static VALUE
nucomp_f_complex(int argc,VALUE * argv,VALUE klass)468 nucomp_f_complex(int argc, VALUE *argv, VALUE klass)
469 {
470     VALUE a1, a2, opts = Qnil;
471     int raise = TRUE;
472 
473     if (rb_scan_args(argc, argv, "11:", &a1, &a2, &opts) == 1) {
474         a2 = Qundef;
475     }
476     if (!NIL_P(opts)) {
477         static ID kwds[1];
478         VALUE exception;
479         if (!kwds[0]) {
480             kwds[0] = idException;
481         }
482         rb_get_kwargs(opts, kwds, 0, 1, &exception);
483         raise = (exception != Qfalse);
484     }
485     return nucomp_convert(rb_cComplex, a1, a2, raise);
486 }
487 
488 #define imp1(n) \
489 inline static VALUE \
490 m_##n##_bang(VALUE x)\
491 {\
492     return rb_math_##n(x);\
493 }
494 
495 imp1(cos)
imp1(cosh)496 imp1(cosh)
497 imp1(exp)
498 
499 static VALUE
500 m_log_bang(VALUE x)
501 {
502     return rb_math_log(1, &x);
503 }
504 
505 imp1(sin)
imp1(sinh)506 imp1(sinh)
507 
508 static VALUE
509 m_cos(VALUE x)
510 {
511     if (!RB_TYPE_P(x, T_COMPLEX))
512 	return m_cos_bang(x);
513     {
514 	get_dat1(x);
515 	return f_complex_new2(rb_cComplex,
516 			      f_mul(m_cos_bang(dat->real),
517 				    m_cosh_bang(dat->imag)),
518 			      f_mul(f_negate(m_sin_bang(dat->real)),
519 				    m_sinh_bang(dat->imag)));
520     }
521 }
522 
523 static VALUE
m_sin(VALUE x)524 m_sin(VALUE x)
525 {
526     if (!RB_TYPE_P(x, T_COMPLEX))
527 	return m_sin_bang(x);
528     {
529 	get_dat1(x);
530 	return f_complex_new2(rb_cComplex,
531 			      f_mul(m_sin_bang(dat->real),
532 				    m_cosh_bang(dat->imag)),
533 			      f_mul(m_cos_bang(dat->real),
534 				    m_sinh_bang(dat->imag)));
535     }
536 }
537 
538 static VALUE
f_complex_polar(VALUE klass,VALUE x,VALUE y)539 f_complex_polar(VALUE klass, VALUE x, VALUE y)
540 {
541     assert(!RB_TYPE_P(x, T_COMPLEX));
542     assert(!RB_TYPE_P(y, T_COMPLEX));
543     if (f_zero_p(x) || f_zero_p(y)) {
544 	if (canonicalization) return x;
545 	return nucomp_s_new_internal(klass, x, RFLOAT_0);
546     }
547     if (RB_FLOAT_TYPE_P(y)) {
548 	const double arg = RFLOAT_VALUE(y);
549 	if (arg == M_PI) {
550 	    x = f_negate(x);
551 	    if (canonicalization) return x;
552 	    y = RFLOAT_0;
553 	}
554 	else if (arg == M_PI_2) {
555 	    y = x;
556 	    x = RFLOAT_0;
557 	}
558 	else if (arg == M_PI_2+M_PI) {
559 	    y = f_negate(x);
560 	    x = RFLOAT_0;
561 	}
562 	else if (RB_FLOAT_TYPE_P(x)) {
563 	    const double abs = RFLOAT_VALUE(x);
564 	    const double real = abs * cos(arg), imag = abs * sin(arg);
565 	    x = DBL2NUM(real);
566 	    if (canonicalization && imag == 0.0) return x;
567 	    y = DBL2NUM(imag);
568 	}
569 	else {
570 	    y = f_mul(x, DBL2NUM(sin(arg)));
571 	    x = f_mul(x, DBL2NUM(cos(arg)));
572 	    if (canonicalization && f_zero_p(y)) return x;
573 	}
574 	return nucomp_s_new_internal(klass, x, y);
575     }
576     return nucomp_s_canonicalize_internal(klass,
577 					  f_mul(x, m_cos(y)),
578 					  f_mul(x, m_sin(y)));
579 }
580 
581 /* returns a Complex or Float of ang*PI-rotated abs */
582 VALUE
rb_dbl_complex_new_polar_pi(double abs,double ang)583 rb_dbl_complex_new_polar_pi(double abs, double ang)
584 {
585     double fi;
586     const double fr = modf(ang, &fi);
587     int pos = fr == +0.5;
588 
589     if (pos || fr == -0.5) {
590 	if ((modf(fi / 2.0, &fi) != fr) ^ pos) abs = -abs;
591 	return rb_complex_new(RFLOAT_0, DBL2NUM(abs));
592     }
593     else if (fr == 0.0) {
594 	if (modf(fi / 2.0, &fi) != 0.0) abs = -abs;
595 	return DBL2NUM(abs);
596     }
597     else {
598 	ang *= M_PI;
599 	return rb_complex_new(DBL2NUM(abs * cos(ang)), DBL2NUM(abs * sin(ang)));
600     }
601 }
602 
603 /*
604  * call-seq:
605  *    Complex.polar(abs[, arg])  ->  complex
606  *
607  * Returns a complex object which denotes the given polar form.
608  *
609  *    Complex.polar(3, 0)            #=> (3.0+0.0i)
610  *    Complex.polar(3, Math::PI/2)   #=> (1.836909530733566e-16+3.0i)
611  *    Complex.polar(3, Math::PI)     #=> (-3.0+3.673819061467132e-16i)
612  *    Complex.polar(3, -Math::PI/2)  #=> (1.836909530733566e-16-3.0i)
613  */
614 static VALUE
nucomp_s_polar(int argc,VALUE * argv,VALUE klass)615 nucomp_s_polar(int argc, VALUE *argv, VALUE klass)
616 {
617     VALUE abs, arg;
618 
619     switch (rb_scan_args(argc, argv, "11", &abs, &arg)) {
620       case 1:
621 	nucomp_real_check(abs);
622 	if (canonicalization) return abs;
623 	return nucomp_s_new_internal(klass, abs, ZERO);
624       default:
625 	nucomp_real_check(abs);
626 	nucomp_real_check(arg);
627 	break;
628     }
629     return f_complex_polar(klass, abs, arg);
630 }
631 
632 /*
633  * call-seq:
634  *    cmp.real  ->  real
635  *
636  * Returns the real part.
637  *
638  *    Complex(7).real      #=> 7
639  *    Complex(9, -4).real  #=> 9
640  */
641 VALUE
rb_complex_real(VALUE self)642 rb_complex_real(VALUE self)
643 {
644     get_dat1(self);
645     return dat->real;
646 }
647 
648 /*
649  * call-seq:
650  *    cmp.imag       ->  real
651  *    cmp.imaginary  ->  real
652  *
653  * Returns the imaginary part.
654  *
655  *    Complex(7).imaginary      #=> 0
656  *    Complex(9, -4).imaginary  #=> -4
657  */
658 VALUE
rb_complex_imag(VALUE self)659 rb_complex_imag(VALUE self)
660 {
661     get_dat1(self);
662     return dat->imag;
663 }
664 
665 /*
666  * call-seq:
667  *    -cmp  ->  complex
668  *
669  * Returns negation of the value.
670  *
671  *    -Complex(1, 2)  #=> (-1-2i)
672  */
673 VALUE
rb_complex_uminus(VALUE self)674 rb_complex_uminus(VALUE self)
675 {
676     get_dat1(self);
677     return f_complex_new2(CLASS_OF(self),
678 			  f_negate(dat->real), f_negate(dat->imag));
679 }
680 
681 /*
682  * call-seq:
683  *    cmp + numeric  ->  complex
684  *
685  * Performs addition.
686  *
687  *    Complex(2, 3)  + Complex(2, 3)   #=> (4+6i)
688  *    Complex(900)   + Complex(1)      #=> (901+0i)
689  *    Complex(-2, 9) + Complex(-9, 2)  #=> (-11+11i)
690  *    Complex(9, 8)  + 4               #=> (13+8i)
691  *    Complex(20, 9) + 9.8             #=> (29.8+9i)
692  */
693 VALUE
rb_complex_plus(VALUE self,VALUE other)694 rb_complex_plus(VALUE self, VALUE other)
695 {
696     if (RB_TYPE_P(other, T_COMPLEX)) {
697 	VALUE real, imag;
698 
699 	get_dat2(self, other);
700 
701 	real = f_add(adat->real, bdat->real);
702 	imag = f_add(adat->imag, bdat->imag);
703 
704 	return f_complex_new2(CLASS_OF(self), real, imag);
705     }
706     if (k_numeric_p(other) && f_real_p(other)) {
707 	get_dat1(self);
708 
709 	return f_complex_new2(CLASS_OF(self),
710 			      f_add(dat->real, other), dat->imag);
711     }
712     return rb_num_coerce_bin(self, other, '+');
713 }
714 
715 /*
716  * call-seq:
717  *    cmp - numeric  ->  complex
718  *
719  * Performs subtraction.
720  *
721  *    Complex(2, 3)  - Complex(2, 3)   #=> (0+0i)
722  *    Complex(900)   - Complex(1)      #=> (899+0i)
723  *    Complex(-2, 9) - Complex(-9, 2)  #=> (7+7i)
724  *    Complex(9, 8)  - 4               #=> (5+8i)
725  *    Complex(20, 9) - 9.8             #=> (10.2+9i)
726  */
727 VALUE
rb_complex_minus(VALUE self,VALUE other)728 rb_complex_minus(VALUE self, VALUE other)
729 {
730     if (RB_TYPE_P(other, T_COMPLEX)) {
731 	VALUE real, imag;
732 
733 	get_dat2(self, other);
734 
735 	real = f_sub(adat->real, bdat->real);
736 	imag = f_sub(adat->imag, bdat->imag);
737 
738 	return f_complex_new2(CLASS_OF(self), real, imag);
739     }
740     if (k_numeric_p(other) && f_real_p(other)) {
741 	get_dat1(self);
742 
743 	return f_complex_new2(CLASS_OF(self),
744 			      f_sub(dat->real, other), dat->imag);
745     }
746     return rb_num_coerce_bin(self, other, '-');
747 }
748 
749 static VALUE
safe_mul(VALUE a,VALUE b,int az,int bz)750 safe_mul(VALUE a, VALUE b, int az, int bz)
751 {
752     double v;
753     if (!az && bz && RB_FLOAT_TYPE_P(a) && (v = RFLOAT_VALUE(a), !isnan(v))) {
754 	a = signbit(v) ? DBL2NUM(-1.0) : DBL2NUM(1.0);
755     }
756     if (!bz && az && RB_FLOAT_TYPE_P(b) && (v = RFLOAT_VALUE(b), !isnan(v))) {
757 	b = signbit(v) ? DBL2NUM(-1.0) : DBL2NUM(1.0);
758     }
759     return f_mul(a, b);
760 }
761 
762 static void
comp_mul(VALUE areal,VALUE aimag,VALUE breal,VALUE bimag,VALUE * real,VALUE * imag)763 comp_mul(VALUE areal, VALUE aimag, VALUE breal, VALUE bimag, VALUE *real, VALUE *imag)
764 {
765     int arzero = f_zero_p(areal);
766     int aizero = f_zero_p(aimag);
767     int brzero = f_zero_p(breal);
768     int bizero = f_zero_p(bimag);
769     *real = f_sub(safe_mul(areal, breal, arzero, brzero),
770                   safe_mul(aimag, bimag, aizero, bizero));
771     *imag = f_add(safe_mul(areal, bimag, arzero, bizero),
772                   safe_mul(aimag, breal, aizero, brzero));
773 }
774 
775 /*
776  * call-seq:
777  *    cmp * numeric  ->  complex
778  *
779  * Performs multiplication.
780  *
781  *    Complex(2, 3)  * Complex(2, 3)   #=> (-5+12i)
782  *    Complex(900)   * Complex(1)      #=> (900+0i)
783  *    Complex(-2, 9) * Complex(-9, 2)  #=> (0-85i)
784  *    Complex(9, 8)  * 4               #=> (36+32i)
785  *    Complex(20, 9) * 9.8             #=> (196.0+88.2i)
786  */
787 VALUE
rb_complex_mul(VALUE self,VALUE other)788 rb_complex_mul(VALUE self, VALUE other)
789 {
790     if (RB_TYPE_P(other, T_COMPLEX)) {
791 	VALUE real, imag;
792 	get_dat2(self, other);
793 
794         comp_mul(adat->real, adat->imag, bdat->real, bdat->imag, &real, &imag);
795 
796 	return f_complex_new2(CLASS_OF(self), real, imag);
797     }
798     if (k_numeric_p(other) && f_real_p(other)) {
799 	get_dat1(self);
800 
801 	return f_complex_new2(CLASS_OF(self),
802 			      f_mul(dat->real, other),
803 			      f_mul(dat->imag, other));
804     }
805     return rb_num_coerce_bin(self, other, '*');
806 }
807 
808 inline static VALUE
f_divide(VALUE self,VALUE other,VALUE (* func)(VALUE,VALUE),ID id)809 f_divide(VALUE self, VALUE other,
810 	 VALUE (*func)(VALUE, VALUE), ID id)
811 {
812     if (RB_TYPE_P(other, T_COMPLEX)) {
813         VALUE r, n, x, y;
814 	int flo;
815 	get_dat2(self, other);
816 
817 	flo = (RB_FLOAT_TYPE_P(adat->real) || RB_FLOAT_TYPE_P(adat->imag) ||
818 	       RB_FLOAT_TYPE_P(bdat->real) || RB_FLOAT_TYPE_P(bdat->imag));
819 
820 	if (f_gt_p(f_abs(bdat->real), f_abs(bdat->imag))) {
821 	    r = (*func)(bdat->imag, bdat->real);
822 	    n = f_mul(bdat->real, f_add(ONE, f_mul(r, r)));
823 	    if (flo)
824 		return f_complex_new2(CLASS_OF(self),
825 				      (*func)(self, n),
826 				      (*func)(f_negate(f_mul(self, r)), n));
827             x = (*func)(f_add(adat->real, f_mul(adat->imag, r)), n);
828             y = (*func)(f_sub(adat->imag, f_mul(adat->real, r)), n);
829 	}
830 	else {
831 	    r = (*func)(bdat->real, bdat->imag);
832 	    n = f_mul(bdat->imag, f_add(ONE, f_mul(r, r)));
833 	    if (flo)
834 		return f_complex_new2(CLASS_OF(self),
835 				      (*func)(f_mul(self, r), n),
836 				      (*func)(f_negate(self), n));
837             x = (*func)(f_add(f_mul(adat->real, r), adat->imag), n);
838             y = (*func)(f_sub(f_mul(adat->imag, r), adat->real), n);
839 	}
840         x = rb_rational_canonicalize(x);
841         y = rb_rational_canonicalize(y);
842         return f_complex_new2(CLASS_OF(self), x, y);
843     }
844     if (k_numeric_p(other) && f_real_p(other)) {
845 	get_dat1(self);
846 
847 	return f_complex_new2(CLASS_OF(self),
848 			      (*func)(dat->real, other),
849 			      (*func)(dat->imag, other));
850     }
851     return rb_num_coerce_bin(self, other, id);
852 }
853 
854 #define rb_raise_zerodiv() rb_raise(rb_eZeroDivError, "divided by 0")
855 
856 /*
857  * call-seq:
858  *    cmp / numeric     ->  complex
859  *    cmp.quo(numeric)  ->  complex
860  *
861  * Performs division.
862  *
863  *    Complex(2, 3)  / Complex(2, 3)   #=> ((1/1)+(0/1)*i)
864  *    Complex(900)   / Complex(1)      #=> ((900/1)+(0/1)*i)
865  *    Complex(-2, 9) / Complex(-9, 2)  #=> ((36/85)-(77/85)*i)
866  *    Complex(9, 8)  / 4               #=> ((9/4)+(2/1)*i)
867  *    Complex(20, 9) / 9.8             #=> (2.0408163265306123+0.9183673469387754i)
868  */
869 VALUE
rb_complex_div(VALUE self,VALUE other)870 rb_complex_div(VALUE self, VALUE other)
871 {
872     return f_divide(self, other, f_quo, id_quo);
873 }
874 
875 #define nucomp_quo rb_complex_div
876 
877 /*
878  * call-seq:
879  *    cmp.fdiv(numeric)  ->  complex
880  *
881  * Performs division as each part is a float, never returns a float.
882  *
883  *    Complex(11, 22).fdiv(3)  #=> (3.6666666666666665+7.333333333333333i)
884  */
885 static VALUE
nucomp_fdiv(VALUE self,VALUE other)886 nucomp_fdiv(VALUE self, VALUE other)
887 {
888     return f_divide(self, other, f_fdiv, id_fdiv);
889 }
890 
891 inline static VALUE
f_reciprocal(VALUE x)892 f_reciprocal(VALUE x)
893 {
894     return f_quo(ONE, x);
895 }
896 
897 /*
898  * call-seq:
899  *    cmp ** numeric  ->  complex
900  *
901  * Performs exponentiation.
902  *
903  *    Complex('i') ** 2              #=> (-1+0i)
904  *    Complex(-8) ** Rational(1, 3)  #=> (1.0000000000000002+1.7320508075688772i)
905  */
906 VALUE
rb_complex_pow(VALUE self,VALUE other)907 rb_complex_pow(VALUE self, VALUE other)
908 {
909     if (k_numeric_p(other) && k_exact_zero_p(other))
910 	return f_complex_new_bang1(CLASS_OF(self), ONE);
911 
912     if (RB_TYPE_P(other, T_RATIONAL) && RRATIONAL(other)->den == LONG2FIX(1))
913 	other = RRATIONAL(other)->num; /* c14n */
914 
915     if (RB_TYPE_P(other, T_COMPLEX)) {
916 	get_dat1(other);
917 
918 	if (k_exact_zero_p(dat->imag))
919 	    other = dat->real; /* c14n */
920     }
921 
922     if (RB_TYPE_P(other, T_COMPLEX)) {
923 	VALUE r, theta, nr, ntheta;
924 
925 	get_dat1(other);
926 
927 	r = f_abs(self);
928 	theta = f_arg(self);
929 
930 	nr = m_exp_bang(f_sub(f_mul(dat->real, m_log_bang(r)),
931 			      f_mul(dat->imag, theta)));
932 	ntheta = f_add(f_mul(theta, dat->real),
933 		       f_mul(dat->imag, m_log_bang(r)));
934 	return f_complex_polar(CLASS_OF(self), nr, ntheta);
935     }
936     if (FIXNUM_P(other)) {
937         long n = FIX2LONG(other);
938         if (n == 0) {
939             return nucomp_s_new_internal(CLASS_OF(self), ONE, ZERO);
940         }
941         if (n < 0) {
942             self = f_reciprocal(self);
943             other = rb_int_uminus(other);
944             n = -n;
945         }
946         {
947             get_dat1(self);
948             VALUE xr = dat->real, xi = dat->imag, zr = xr, zi = xi;
949 
950             if (f_zero_p(xi)) {
951                 zr = rb_num_pow(zr, other);
952             }
953             else if (f_zero_p(xr)) {
954                 zi = rb_num_pow(zi, other);
955                 if (n & 2) zi = f_negate(zi);
956                 if (!(n & 1)) {
957                     VALUE tmp = zr;
958                     zr = zi;
959                     zi = tmp;
960                 }
961             }
962             else {
963                 while (--n) {
964                     long q, r;
965 
966                     for (; q = n / 2, r = n % 2, r == 0; n = q) {
967                         VALUE tmp = f_sub(f_mul(xr, xr), f_mul(xi, xi));
968                         xi = f_mul(f_mul(TWO, xr), xi);
969                         xr = tmp;
970                     }
971                     comp_mul(zr, zi, xr, xi, &zr, &zi);
972                 }
973             }
974             return nucomp_s_new_internal(CLASS_OF(self), zr, zi);
975 	}
976     }
977     if (k_numeric_p(other) && f_real_p(other)) {
978 	VALUE r, theta;
979 
980 	if (RB_TYPE_P(other, T_BIGNUM))
981 	    rb_warn("in a**b, b may be too big");
982 
983 	r = f_abs(self);
984 	theta = f_arg(self);
985 
986 	return f_complex_polar(CLASS_OF(self), f_expt(r, other),
987 			       f_mul(theta, other));
988     }
989     return rb_num_coerce_bin(self, other, id_expt);
990 }
991 
992 /*
993  * call-seq:
994  *    cmp == object  ->  true or false
995  *
996  * Returns true if cmp equals object numerically.
997  *
998  *    Complex(2, 3)  == Complex(2, 3)   #=> true
999  *    Complex(5)     == 5               #=> true
1000  *    Complex(0)     == 0.0             #=> true
1001  *    Complex('1/3') == 0.33            #=> false
1002  *    Complex('1/2') == '1/2'           #=> false
1003  */
1004 static VALUE
nucomp_eqeq_p(VALUE self,VALUE other)1005 nucomp_eqeq_p(VALUE self, VALUE other)
1006 {
1007     if (RB_TYPE_P(other, T_COMPLEX)) {
1008 	get_dat2(self, other);
1009 
1010 	return f_boolcast(f_eqeq_p(adat->real, bdat->real) &&
1011 			  f_eqeq_p(adat->imag, bdat->imag));
1012     }
1013     if (k_numeric_p(other) && f_real_p(other)) {
1014 	get_dat1(self);
1015 
1016 	return f_boolcast(f_eqeq_p(dat->real, other) && f_zero_p(dat->imag));
1017     }
1018     return f_boolcast(f_eqeq_p(other, self));
1019 }
1020 
1021 /* :nodoc: */
1022 static VALUE
nucomp_coerce(VALUE self,VALUE other)1023 nucomp_coerce(VALUE self, VALUE other)
1024 {
1025     if (k_numeric_p(other) && f_real_p(other))
1026 	return rb_assoc_new(f_complex_new_bang1(CLASS_OF(self), other), self);
1027     if (RB_TYPE_P(other, T_COMPLEX))
1028 	return rb_assoc_new(other, self);
1029 
1030     rb_raise(rb_eTypeError, "%"PRIsVALUE" can't be coerced into %"PRIsVALUE,
1031 	     rb_obj_class(other), rb_obj_class(self));
1032     return Qnil;
1033 }
1034 
1035 /*
1036  * call-seq:
1037  *    cmp.abs        ->  real
1038  *    cmp.magnitude  ->  real
1039  *
1040  * Returns the absolute part of its polar form.
1041  *
1042  *    Complex(-1).abs         #=> 1
1043  *    Complex(3.0, -4.0).abs  #=> 5.0
1044  */
1045 VALUE
rb_complex_abs(VALUE self)1046 rb_complex_abs(VALUE self)
1047 {
1048     get_dat1(self);
1049 
1050     if (f_zero_p(dat->real)) {
1051 	VALUE a = f_abs(dat->imag);
1052 	if (RB_FLOAT_TYPE_P(dat->real) && !RB_FLOAT_TYPE_P(dat->imag))
1053 	    a = f_to_f(a);
1054 	return a;
1055     }
1056     if (f_zero_p(dat->imag)) {
1057 	VALUE a = f_abs(dat->real);
1058 	if (!RB_FLOAT_TYPE_P(dat->real) && RB_FLOAT_TYPE_P(dat->imag))
1059 	    a = f_to_f(a);
1060 	return a;
1061     }
1062     return rb_math_hypot(dat->real, dat->imag);
1063 }
1064 
1065 /*
1066  * call-seq:
1067  *    cmp.abs2  ->  real
1068  *
1069  * Returns square of the absolute value.
1070  *
1071  *    Complex(-1).abs2         #=> 1
1072  *    Complex(3.0, -4.0).abs2  #=> 25.0
1073  */
1074 static VALUE
nucomp_abs2(VALUE self)1075 nucomp_abs2(VALUE self)
1076 {
1077     get_dat1(self);
1078     return f_add(f_mul(dat->real, dat->real),
1079 		 f_mul(dat->imag, dat->imag));
1080 }
1081 
1082 /*
1083  * call-seq:
1084  *    cmp.arg    ->  float
1085  *    cmp.angle  ->  float
1086  *    cmp.phase  ->  float
1087  *
1088  * Returns the angle part of its polar form.
1089  *
1090  *    Complex.polar(3, Math::PI/2).arg  #=> 1.5707963267948966
1091  */
1092 VALUE
rb_complex_arg(VALUE self)1093 rb_complex_arg(VALUE self)
1094 {
1095     get_dat1(self);
1096     return rb_math_atan2(dat->imag, dat->real);
1097 }
1098 
1099 /*
1100  * call-seq:
1101  *    cmp.rect         ->  array
1102  *    cmp.rectangular  ->  array
1103  *
1104  * Returns an array; [cmp.real, cmp.imag].
1105  *
1106  *    Complex(1, 2).rectangular  #=> [1, 2]
1107  */
1108 static VALUE
nucomp_rect(VALUE self)1109 nucomp_rect(VALUE self)
1110 {
1111     get_dat1(self);
1112     return rb_assoc_new(dat->real, dat->imag);
1113 }
1114 
1115 /*
1116  * call-seq:
1117  *    cmp.polar  ->  array
1118  *
1119  * Returns an array; [cmp.abs, cmp.arg].
1120  *
1121  *    Complex(1, 2).polar  #=> [2.23606797749979, 1.1071487177940904]
1122  */
1123 static VALUE
nucomp_polar(VALUE self)1124 nucomp_polar(VALUE self)
1125 {
1126     return rb_assoc_new(f_abs(self), f_arg(self));
1127 }
1128 
1129 /*
1130  * call-seq:
1131  *    cmp.conj       ->  complex
1132  *    cmp.conjugate  ->  complex
1133  *
1134  * Returns the complex conjugate.
1135  *
1136  *    Complex(1, 2).conjugate  #=> (1-2i)
1137  */
1138 VALUE
rb_complex_conjugate(VALUE self)1139 rb_complex_conjugate(VALUE self)
1140 {
1141     get_dat1(self);
1142     return f_complex_new2(CLASS_OF(self), dat->real, f_negate(dat->imag));
1143 }
1144 
1145 /*
1146  * call-seq:
1147  *    cmp.real?  ->  false
1148  *
1149  * Returns false.
1150  */
1151 static VALUE
nucomp_false(VALUE self)1152 nucomp_false(VALUE self)
1153 {
1154     return Qfalse;
1155 }
1156 
1157 /*
1158  * call-seq:
1159  *    cmp.denominator  ->  integer
1160  *
1161  * Returns the denominator (lcm of both denominator - real and imag).
1162  *
1163  * See numerator.
1164  */
1165 static VALUE
nucomp_denominator(VALUE self)1166 nucomp_denominator(VALUE self)
1167 {
1168     get_dat1(self);
1169     return rb_lcm(f_denominator(dat->real), f_denominator(dat->imag));
1170 }
1171 
1172 /*
1173  * call-seq:
1174  *    cmp.numerator  ->  numeric
1175  *
1176  * Returns the numerator.
1177  *
1178  *        1   2       3+4i  <-  numerator
1179  *        - + -i  ->  ----
1180  *        2   3        6    <-  denominator
1181  *
1182  *    c = Complex('1/2+2/3i')  #=> ((1/2)+(2/3)*i)
1183  *    n = c.numerator          #=> (3+4i)
1184  *    d = c.denominator        #=> 6
1185  *    n / d                    #=> ((1/2)+(2/3)*i)
1186  *    Complex(Rational(n.real, d), Rational(n.imag, d))
1187  *                             #=> ((1/2)+(2/3)*i)
1188  * See denominator.
1189  */
1190 static VALUE
nucomp_numerator(VALUE self)1191 nucomp_numerator(VALUE self)
1192 {
1193     VALUE cd;
1194 
1195     get_dat1(self);
1196 
1197     cd = f_denominator(self);
1198     return f_complex_new2(CLASS_OF(self),
1199 			  f_mul(f_numerator(dat->real),
1200 				f_div(cd, f_denominator(dat->real))),
1201 			  f_mul(f_numerator(dat->imag),
1202 				f_div(cd, f_denominator(dat->imag))));
1203 }
1204 
1205 /* :nodoc: */
1206 static VALUE
nucomp_hash(VALUE self)1207 nucomp_hash(VALUE self)
1208 {
1209     st_index_t v, h[2];
1210     VALUE n;
1211 
1212     get_dat1(self);
1213     n = rb_hash(dat->real);
1214     h[0] = NUM2LONG(n);
1215     n = rb_hash(dat->imag);
1216     h[1] = NUM2LONG(n);
1217     v = rb_memhash(h, sizeof(h));
1218     return ST2FIX(v);
1219 }
1220 
1221 /* :nodoc: */
1222 static VALUE
nucomp_eql_p(VALUE self,VALUE other)1223 nucomp_eql_p(VALUE self, VALUE other)
1224 {
1225     if (RB_TYPE_P(other, T_COMPLEX)) {
1226 	get_dat2(self, other);
1227 
1228 	return f_boolcast((CLASS_OF(adat->real) == CLASS_OF(bdat->real)) &&
1229 			  (CLASS_OF(adat->imag) == CLASS_OF(bdat->imag)) &&
1230 			  f_eqeq_p(self, other));
1231 
1232     }
1233     return Qfalse;
1234 }
1235 
1236 inline static int
f_signbit(VALUE x)1237 f_signbit(VALUE x)
1238 {
1239     if (RB_FLOAT_TYPE_P(x)) {
1240 	double f = RFLOAT_VALUE(x);
1241 	return !isnan(f) && signbit(f);
1242     }
1243     return f_negative_p(x);
1244 }
1245 
1246 inline static int
f_tpositive_p(VALUE x)1247 f_tpositive_p(VALUE x)
1248 {
1249     return !f_signbit(x);
1250 }
1251 
1252 static VALUE
f_format(VALUE self,VALUE (* func)(VALUE))1253 f_format(VALUE self, VALUE (*func)(VALUE))
1254 {
1255     VALUE s;
1256     int impos;
1257 
1258     get_dat1(self);
1259 
1260     impos = f_tpositive_p(dat->imag);
1261 
1262     s = (*func)(dat->real);
1263     rb_str_cat2(s, !impos ? "-" : "+");
1264 
1265     rb_str_concat(s, (*func)(f_abs(dat->imag)));
1266     if (!rb_isdigit(RSTRING_PTR(s)[RSTRING_LEN(s) - 1]))
1267 	rb_str_cat2(s, "*");
1268     rb_str_cat2(s, "i");
1269 
1270     return s;
1271 }
1272 
1273 /*
1274  * call-seq:
1275  *    cmp.to_s  ->  string
1276  *
1277  * Returns the value as a string.
1278  *
1279  *    Complex(2).to_s                       #=> "2+0i"
1280  *    Complex('-8/6').to_s                  #=> "-4/3+0i"
1281  *    Complex('1/2i').to_s                  #=> "0+1/2i"
1282  *    Complex(0, Float::INFINITY).to_s      #=> "0+Infinity*i"
1283  *    Complex(Float::NAN, Float::NAN).to_s  #=> "NaN+NaN*i"
1284  */
1285 static VALUE
nucomp_to_s(VALUE self)1286 nucomp_to_s(VALUE self)
1287 {
1288     return f_format(self, rb_String);
1289 }
1290 
1291 /*
1292  * call-seq:
1293  *    cmp.inspect  ->  string
1294  *
1295  * Returns the value as a string for inspection.
1296  *
1297  *    Complex(2).inspect                       #=> "(2+0i)"
1298  *    Complex('-8/6').inspect                  #=> "((-4/3)+0i)"
1299  *    Complex('1/2i').inspect                  #=> "(0+(1/2)*i)"
1300  *    Complex(0, Float::INFINITY).inspect      #=> "(0+Infinity*i)"
1301  *    Complex(Float::NAN, Float::NAN).inspect  #=> "(NaN+NaN*i)"
1302  */
1303 static VALUE
nucomp_inspect(VALUE self)1304 nucomp_inspect(VALUE self)
1305 {
1306     VALUE s;
1307 
1308     s = rb_usascii_str_new2("(");
1309     rb_str_concat(s, f_format(self, rb_inspect));
1310     rb_str_cat2(s, ")");
1311 
1312     return s;
1313 }
1314 
1315 #define FINITE_TYPE_P(v) (RB_INTEGER_TYPE_P(v) || RB_TYPE_P(v, T_RATIONAL))
1316 
1317 /*
1318  * call-seq:
1319  *    cmp.finite?  ->  true or false
1320  *
1321  * Returns +true+ if +cmp+'s real and imaginary parts are both finite numbers,
1322  * otherwise returns +false+.
1323  */
1324 static VALUE
rb_complex_finite_p(VALUE self)1325 rb_complex_finite_p(VALUE self)
1326 {
1327     get_dat1(self);
1328 
1329     if (f_finite_p(dat->real) && f_finite_p(dat->imag)) {
1330 	return Qtrue;
1331     }
1332     return Qfalse;
1333 }
1334 
1335 /*
1336  * call-seq:
1337  *    cmp.infinite?  ->  nil or 1
1338  *
1339  * Returns +1+ if +cmp+'s real or imaginary part is an infinite number,
1340  * otherwise returns +nil+.
1341  *
1342  *  For example:
1343  *
1344  *     (1+1i).infinite?                   #=> nil
1345  *     (Float::INFINITY + 1i).infinite?   #=> 1
1346  */
1347 static VALUE
rb_complex_infinite_p(VALUE self)1348 rb_complex_infinite_p(VALUE self)
1349 {
1350     get_dat1(self);
1351 
1352     if (NIL_P(f_infinite_p(dat->real)) && NIL_P(f_infinite_p(dat->imag))) {
1353 	return Qnil;
1354     }
1355     return ONE;
1356 }
1357 
1358 /* :nodoc: */
1359 static VALUE
nucomp_dumper(VALUE self)1360 nucomp_dumper(VALUE self)
1361 {
1362     return self;
1363 }
1364 
1365 /* :nodoc: */
1366 static VALUE
nucomp_loader(VALUE self,VALUE a)1367 nucomp_loader(VALUE self, VALUE a)
1368 {
1369     get_dat1(self);
1370 
1371     RCOMPLEX_SET_REAL(dat, rb_ivar_get(a, id_i_real));
1372     RCOMPLEX_SET_IMAG(dat, rb_ivar_get(a, id_i_imag));
1373     OBJ_FREEZE_RAW(self);
1374 
1375     return self;
1376 }
1377 
1378 /* :nodoc: */
1379 static VALUE
nucomp_marshal_dump(VALUE self)1380 nucomp_marshal_dump(VALUE self)
1381 {
1382     VALUE a;
1383     get_dat1(self);
1384 
1385     a = rb_assoc_new(dat->real, dat->imag);
1386     rb_copy_generic_ivar(a, self);
1387     return a;
1388 }
1389 
1390 /* :nodoc: */
1391 static VALUE
nucomp_marshal_load(VALUE self,VALUE a)1392 nucomp_marshal_load(VALUE self, VALUE a)
1393 {
1394     Check_Type(a, T_ARRAY);
1395     if (RARRAY_LEN(a) != 2)
1396 	rb_raise(rb_eArgError, "marshaled complex must have an array whose length is 2 but %ld", RARRAY_LEN(a));
1397     rb_ivar_set(self, id_i_real, RARRAY_AREF(a, 0));
1398     rb_ivar_set(self, id_i_imag, RARRAY_AREF(a, 1));
1399     return self;
1400 }
1401 
1402 /* --- */
1403 
1404 VALUE
rb_complex_raw(VALUE x,VALUE y)1405 rb_complex_raw(VALUE x, VALUE y)
1406 {
1407     return nucomp_s_new_internal(rb_cComplex, x, y);
1408 }
1409 
1410 VALUE
rb_complex_new(VALUE x,VALUE y)1411 rb_complex_new(VALUE x, VALUE y)
1412 {
1413     return nucomp_s_canonicalize_internal(rb_cComplex, x, y);
1414 }
1415 
1416 VALUE
rb_complex_new_polar(VALUE x,VALUE y)1417 rb_complex_new_polar(VALUE x, VALUE y)
1418 {
1419     return f_complex_polar(rb_cComplex, x, y);
1420 }
1421 
1422 VALUE
rb_complex_polar(VALUE x,VALUE y)1423 rb_complex_polar(VALUE x, VALUE y)
1424 {
1425     return rb_complex_new_polar(x, y);
1426 }
1427 
1428 VALUE
rb_Complex(VALUE x,VALUE y)1429 rb_Complex(VALUE x, VALUE y)
1430 {
1431     VALUE a[2];
1432     a[0] = x;
1433     a[1] = y;
1434     return nucomp_s_convert(2, a, rb_cComplex);
1435 }
1436 
1437 /*!
1438  * Creates a Complex object.
1439  *
1440  * \param real    real part value
1441  * \param imag    imaginary part value
1442  * \return        a new Complex object
1443  */
1444 VALUE
rb_dbl_complex_new(double real,double imag)1445 rb_dbl_complex_new(double real, double imag)
1446 {
1447     return rb_complex_raw(DBL2NUM(real), DBL2NUM(imag));
1448 }
1449 
1450 /*
1451  * call-seq:
1452  *    cmp.to_i  ->  integer
1453  *
1454  * Returns the value as an integer if possible (the imaginary part
1455  * should be exactly zero).
1456  *
1457  *    Complex(1, 0).to_i    #=> 1
1458  *    Complex(1, 0.0).to_i  # RangeError
1459  *    Complex(1, 2).to_i    # RangeError
1460  */
1461 static VALUE
nucomp_to_i(VALUE self)1462 nucomp_to_i(VALUE self)
1463 {
1464     get_dat1(self);
1465 
1466     if (!k_exact_zero_p(dat->imag)) {
1467 	rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Integer",
1468 		 self);
1469     }
1470     return f_to_i(dat->real);
1471 }
1472 
1473 /*
1474  * call-seq:
1475  *    cmp.to_f  ->  float
1476  *
1477  * Returns the value as a float if possible (the imaginary part should
1478  * be exactly zero).
1479  *
1480  *    Complex(1, 0).to_f    #=> 1.0
1481  *    Complex(1, 0.0).to_f  # RangeError
1482  *    Complex(1, 2).to_f    # RangeError
1483  */
1484 static VALUE
nucomp_to_f(VALUE self)1485 nucomp_to_f(VALUE self)
1486 {
1487     get_dat1(self);
1488 
1489     if (!k_exact_zero_p(dat->imag)) {
1490 	rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Float",
1491 		 self);
1492     }
1493     return f_to_f(dat->real);
1494 }
1495 
1496 /*
1497  * call-seq:
1498  *    cmp.to_r  ->  rational
1499  *
1500  * Returns the value as a rational if possible (the imaginary part
1501  * should be exactly zero).
1502  *
1503  *    Complex(1, 0).to_r    #=> (1/1)
1504  *    Complex(1, 0.0).to_r  # RangeError
1505  *    Complex(1, 2).to_r    # RangeError
1506  *
1507  * See rationalize.
1508  */
1509 static VALUE
nucomp_to_r(VALUE self)1510 nucomp_to_r(VALUE self)
1511 {
1512     get_dat1(self);
1513 
1514     if (!k_exact_zero_p(dat->imag)) {
1515 	rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Rational",
1516 		 self);
1517     }
1518     return f_to_r(dat->real);
1519 }
1520 
1521 /*
1522  * call-seq:
1523  *    cmp.rationalize([eps])  ->  rational
1524  *
1525  * Returns the value as a rational if possible (the imaginary part
1526  * should be exactly zero).
1527  *
1528  *    Complex(1.0/3, 0).rationalize  #=> (1/3)
1529  *    Complex(1, 0.0).rationalize    # RangeError
1530  *    Complex(1, 2).rationalize      # RangeError
1531  *
1532  * See to_r.
1533  */
1534 static VALUE
nucomp_rationalize(int argc,VALUE * argv,VALUE self)1535 nucomp_rationalize(int argc, VALUE *argv, VALUE self)
1536 {
1537     get_dat1(self);
1538 
1539     rb_check_arity(argc, 0, 1);
1540 
1541     if (!k_exact_zero_p(dat->imag)) {
1542        rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Rational",
1543                 self);
1544     }
1545     return rb_funcallv(dat->real, id_rationalize, argc, argv);
1546 }
1547 
1548 /*
1549  * call-seq:
1550  *    complex.to_c  ->  self
1551  *
1552  * Returns self.
1553  *
1554  *    Complex(2).to_c      #=> (2+0i)
1555  *    Complex(-8, 6).to_c  #=> (-8+6i)
1556  */
1557 static VALUE
nucomp_to_c(VALUE self)1558 nucomp_to_c(VALUE self)
1559 {
1560     return self;
1561 }
1562 
1563 /*
1564  * call-seq:
1565  *    nil.to_c  ->  (0+0i)
1566  *
1567  * Returns zero as a complex.
1568  */
1569 static VALUE
nilclass_to_c(VALUE self)1570 nilclass_to_c(VALUE self)
1571 {
1572     return rb_complex_new1(INT2FIX(0));
1573 }
1574 
1575 /*
1576  * call-seq:
1577  *    num.to_c  ->  complex
1578  *
1579  * Returns the value as a complex.
1580  */
1581 static VALUE
numeric_to_c(VALUE self)1582 numeric_to_c(VALUE self)
1583 {
1584     return rb_complex_new1(self);
1585 }
1586 
1587 #include <ctype.h>
1588 
1589 inline static int
issign(int c)1590 issign(int c)
1591 {
1592     return (c == '-' || c == '+');
1593 }
1594 
1595 static int
read_sign(const char ** s,char ** b)1596 read_sign(const char **s,
1597 	  char **b)
1598 {
1599     int sign = '?';
1600 
1601     if (issign(**s)) {
1602 	sign = **b = **s;
1603 	(*s)++;
1604 	(*b)++;
1605     }
1606     return sign;
1607 }
1608 
1609 inline static int
isdecimal(int c)1610 isdecimal(int c)
1611 {
1612     return isdigit((unsigned char)c);
1613 }
1614 
1615 static int
read_digits(const char ** s,int strict,char ** b)1616 read_digits(const char **s, int strict,
1617 	    char **b)
1618 {
1619     int us = 1;
1620 
1621     if (!isdecimal(**s))
1622 	return 0;
1623 
1624     while (isdecimal(**s) || **s == '_') {
1625 	if (**s == '_') {
1626 	    if (strict) {
1627 		if (us)
1628 		    return 0;
1629 	    }
1630 	    us = 1;
1631 	}
1632 	else {
1633 	    **b = **s;
1634 	    (*b)++;
1635 	    us = 0;
1636 	}
1637 	(*s)++;
1638     }
1639     if (us)
1640 	do {
1641 	    (*s)--;
1642 	} while (**s == '_');
1643     return 1;
1644 }
1645 
1646 inline static int
islettere(int c)1647 islettere(int c)
1648 {
1649     return (c == 'e' || c == 'E');
1650 }
1651 
1652 static int
read_num(const char ** s,int strict,char ** b)1653 read_num(const char **s, int strict,
1654 	 char **b)
1655 {
1656     if (**s != '.') {
1657 	if (!read_digits(s, strict, b))
1658 	    return 0;
1659     }
1660 
1661     if (**s == '.') {
1662 	**b = **s;
1663 	(*s)++;
1664 	(*b)++;
1665 	if (!read_digits(s, strict, b)) {
1666 	    (*b)--;
1667 	    return 0;
1668 	}
1669     }
1670 
1671     if (islettere(**s)) {
1672 	**b = **s;
1673 	(*s)++;
1674 	(*b)++;
1675 	read_sign(s, b);
1676 	if (!read_digits(s, strict, b)) {
1677 	    (*b)--;
1678 	    return 0;
1679 	}
1680     }
1681     return 1;
1682 }
1683 
1684 inline static int
read_den(const char ** s,int strict,char ** b)1685 read_den(const char **s, int strict,
1686 	 char **b)
1687 {
1688     if (!read_digits(s, strict, b))
1689 	return 0;
1690     return 1;
1691 }
1692 
1693 static int
read_rat_nos(const char ** s,int strict,char ** b)1694 read_rat_nos(const char **s, int strict,
1695 	     char **b)
1696 {
1697     if (!read_num(s, strict, b))
1698 	return 0;
1699     if (**s == '/') {
1700 	**b = **s;
1701 	(*s)++;
1702 	(*b)++;
1703 	if (!read_den(s, strict, b)) {
1704 	    (*b)--;
1705 	    return 0;
1706 	}
1707     }
1708     return 1;
1709 }
1710 
1711 static int
read_rat(const char ** s,int strict,char ** b)1712 read_rat(const char **s, int strict,
1713 	 char **b)
1714 {
1715     read_sign(s, b);
1716     if (!read_rat_nos(s, strict, b))
1717 	return 0;
1718     return 1;
1719 }
1720 
1721 inline static int
isimagunit(int c)1722 isimagunit(int c)
1723 {
1724     return (c == 'i' || c == 'I' ||
1725 	    c == 'j' || c == 'J');
1726 }
1727 
1728 static VALUE
str2num(char * s)1729 str2num(char *s)
1730 {
1731     if (strchr(s, '/'))
1732 	return rb_cstr_to_rat(s, 0);
1733     if (strpbrk(s, ".eE"))
1734 	return DBL2NUM(rb_cstr_to_dbl(s, 0));
1735     return rb_cstr_to_inum(s, 10, 0);
1736 }
1737 
1738 static int
read_comp(const char ** s,int strict,VALUE * ret,char ** b)1739 read_comp(const char **s, int strict,
1740 	  VALUE *ret, char **b)
1741 {
1742     char *bb;
1743     int sign;
1744     VALUE num, num2;
1745 
1746     bb = *b;
1747 
1748     sign = read_sign(s, b);
1749 
1750     if (isimagunit(**s)) {
1751 	(*s)++;
1752 	num = INT2FIX((sign == '-') ? -1 : + 1);
1753 	*ret = rb_complex_new2(ZERO, num);
1754 	return 1; /* e.g. "i" */
1755     }
1756 
1757     if (!read_rat_nos(s, strict, b)) {
1758 	**b = '\0';
1759 	num = str2num(bb);
1760 	*ret = rb_complex_new2(num, ZERO);
1761 	return 0; /* e.g. "-" */
1762     }
1763     **b = '\0';
1764     num = str2num(bb);
1765 
1766     if (isimagunit(**s)) {
1767 	(*s)++;
1768 	*ret = rb_complex_new2(ZERO, num);
1769 	return 1; /* e.g. "3i" */
1770     }
1771 
1772     if (**s == '@') {
1773 	int st;
1774 
1775 	(*s)++;
1776 	bb = *b;
1777 	st = read_rat(s, strict, b);
1778 	**b = '\0';
1779 	if (strlen(bb) < 1 ||
1780 	    !isdecimal(*(bb + strlen(bb) - 1))) {
1781 	    *ret = rb_complex_new2(num, ZERO);
1782 	    return 0; /* e.g. "1@-" */
1783 	}
1784 	num2 = str2num(bb);
1785 	*ret = rb_complex_new_polar(num, num2);
1786 	if (!st)
1787 	    return 0; /* e.g. "1@2." */
1788 	else
1789 	    return 1; /* e.g. "1@2" */
1790     }
1791 
1792     if (issign(**s)) {
1793 	bb = *b;
1794 	sign = read_sign(s, b);
1795 	if (isimagunit(**s))
1796 	    num2 = INT2FIX((sign == '-') ? -1 : + 1);
1797 	else {
1798 	    if (!read_rat_nos(s, strict, b)) {
1799 		*ret = rb_complex_new2(num, ZERO);
1800 		return 0; /* e.g. "1+xi" */
1801 	    }
1802 	    **b = '\0';
1803 	    num2 = str2num(bb);
1804 	}
1805 	if (!isimagunit(**s)) {
1806 	    *ret = rb_complex_new2(num, ZERO);
1807 	    return 0; /* e.g. "1+3x" */
1808 	}
1809 	(*s)++;
1810 	*ret = rb_complex_new2(num, num2);
1811 	return 1; /* e.g. "1+2i" */
1812     }
1813     /* !(@, - or +) */
1814     {
1815 	*ret = rb_complex_new2(num, ZERO);
1816 	return 1; /* e.g. "3" */
1817     }
1818 }
1819 
1820 inline static void
skip_ws(const char ** s)1821 skip_ws(const char **s)
1822 {
1823     while (isspace((unsigned char)**s))
1824 	(*s)++;
1825 }
1826 
1827 static int
parse_comp(const char * s,int strict,VALUE * num)1828 parse_comp(const char *s, int strict, VALUE *num)
1829 {
1830     char *buf, *b;
1831     VALUE tmp;
1832     int ret = 1;
1833 
1834     buf = ALLOCV_N(char, tmp, strlen(s) + 1);
1835     b = buf;
1836 
1837     skip_ws(&s);
1838     if (!read_comp(&s, strict, num, &b)) {
1839         ret = 0;
1840     }
1841     else {
1842         skip_ws(&s);
1843 
1844         if (strict)
1845             if (*s != '\0')
1846                 ret = 0;
1847     }
1848     ALLOCV_END(tmp);
1849 
1850     return ret;
1851 }
1852 
1853 static VALUE
string_to_c_strict(VALUE self,int raise)1854 string_to_c_strict(VALUE self, int raise)
1855 {
1856     char *s;
1857     VALUE num;
1858 
1859     rb_must_asciicompat(self);
1860 
1861     s = RSTRING_PTR(self);
1862 
1863     if (!s || memchr(s, '\0', RSTRING_LEN(self))) {
1864         if (!raise) return Qnil;
1865 	rb_raise(rb_eArgError, "string contains null byte");
1866     }
1867 
1868     if (s && s[RSTRING_LEN(self)]) {
1869 	rb_str_modify(self);
1870 	s = RSTRING_PTR(self);
1871 	s[RSTRING_LEN(self)] = '\0';
1872     }
1873 
1874     if (!s)
1875 	s = (char *)"";
1876 
1877     if (!parse_comp(s, 1, &num)) {
1878         if (!raise) return Qnil;
1879 	rb_raise(rb_eArgError, "invalid value for convert(): %+"PRIsVALUE,
1880 		 self);
1881     }
1882 
1883     return num;
1884 }
1885 
1886 /*
1887  * call-seq:
1888  *    str.to_c  ->  complex
1889  *
1890  * Returns a complex which denotes the string form.  The parser
1891  * ignores leading whitespaces and trailing garbage.  Any digit
1892  * sequences can be separated by an underscore.  Returns zero for null
1893  * or garbage string.
1894  *
1895  *    '9'.to_c           #=> (9+0i)
1896  *    '2.5'.to_c         #=> (2.5+0i)
1897  *    '2.5/1'.to_c       #=> ((5/2)+0i)
1898  *    '-3/2'.to_c        #=> ((-3/2)+0i)
1899  *    '-i'.to_c          #=> (0-1i)
1900  *    '45i'.to_c         #=> (0+45i)
1901  *    '3-4i'.to_c        #=> (3-4i)
1902  *    '-4e2-4e-2i'.to_c  #=> (-400.0-0.04i)
1903  *    '-0.0-0.0i'.to_c   #=> (-0.0-0.0i)
1904  *    '1/2+3/4i'.to_c    #=> ((1/2)+(3/4)*i)
1905  *    'ruby'.to_c        #=> (0+0i)
1906  *
1907  * See Kernel.Complex.
1908  */
1909 static VALUE
string_to_c(VALUE self)1910 string_to_c(VALUE self)
1911 {
1912     char *s;
1913     VALUE num;
1914 
1915     rb_must_asciicompat(self);
1916 
1917     s = RSTRING_PTR(self);
1918 
1919     if (s && s[RSTRING_LEN(self)]) {
1920 	rb_str_modify(self);
1921 	s = RSTRING_PTR(self);
1922 	s[RSTRING_LEN(self)] = '\0';
1923     }
1924 
1925     if (!s)
1926 	s = (char *)"";
1927 
1928     (void)parse_comp(s, 0, &num);
1929 
1930     return num;
1931 }
1932 
1933 static VALUE
to_complex(VALUE val)1934 to_complex(VALUE val)
1935 {
1936     return rb_convert_type(val, T_COMPLEX, "Complex", "to_c");
1937 }
1938 
1939 static VALUE
nucomp_convert(VALUE klass,VALUE a1,VALUE a2,int raise)1940 nucomp_convert(VALUE klass, VALUE a1, VALUE a2, int raise)
1941 {
1942     if (NIL_P(a1) || NIL_P(a2)) {
1943         if (!raise) return Qnil;
1944 	rb_raise(rb_eTypeError, "can't convert nil into Complex");
1945     }
1946 
1947     if (RB_TYPE_P(a1, T_STRING)) {
1948 	a1 = string_to_c_strict(a1, raise);
1949         if (NIL_P(a1)) return Qnil;
1950     }
1951 
1952     if (RB_TYPE_P(a2, T_STRING)) {
1953 	a2 = string_to_c_strict(a2, raise);
1954         if (NIL_P(a2)) return Qnil;
1955     }
1956 
1957     if (RB_TYPE_P(a1, T_COMPLEX)) {
1958 	{
1959 	    get_dat1(a1);
1960 
1961 	    if (k_exact_zero_p(dat->imag))
1962 		a1 = dat->real;
1963 	}
1964     }
1965 
1966     if (RB_TYPE_P(a2, T_COMPLEX)) {
1967 	{
1968 	    get_dat1(a2);
1969 
1970 	    if (k_exact_zero_p(dat->imag))
1971 		a2 = dat->real;
1972 	}
1973     }
1974 
1975     if (RB_TYPE_P(a1, T_COMPLEX)) {
1976 	if (a2 == Qundef || (k_exact_zero_p(a2)))
1977 	    return a1;
1978     }
1979 
1980     if (a2 == Qundef) {
1981 	if (k_numeric_p(a1) && !f_real_p(a1))
1982 	    return a1;
1983 	/* should raise exception for consistency */
1984 	if (!k_numeric_p(a1)) {
1985             if (!raise)
1986                 return rb_protect(to_complex, a1, NULL);
1987 	    return to_complex(a1);
1988         }
1989     }
1990     else {
1991 	if ((k_numeric_p(a1) && k_numeric_p(a2)) &&
1992 	    (!f_real_p(a1) || !f_real_p(a2)))
1993 	    return f_add(a1,
1994 			 f_mul(a2,
1995 			       f_complex_new_bang2(rb_cComplex, ZERO, ONE)));
1996     }
1997 
1998     {
1999         int argc;
2000 	VALUE argv2[2];
2001 	argv2[0] = a1;
2002         if (a2 == Qundef) {
2003             argv2[1] = Qnil;
2004             argc = 1;
2005         }
2006         else {
2007             if (!raise && !RB_INTEGER_TYPE_P(a2) && !RB_FLOAT_TYPE_P(a2) && !RB_TYPE_P(a2, T_RATIONAL))
2008                 return Qnil;
2009             argv2[1] = a2;
2010             argc = 2;
2011         }
2012 	return nucomp_s_new(argc, argv2, klass);
2013     }
2014 }
2015 
2016 static VALUE
nucomp_s_convert(int argc,VALUE * argv,VALUE klass)2017 nucomp_s_convert(int argc, VALUE *argv, VALUE klass)
2018 {
2019     VALUE a1, a2;
2020 
2021     if (rb_scan_args(argc, argv, "11", &a1, &a2) == 1) {
2022         a2 = Qundef;
2023     }
2024 
2025     return nucomp_convert(klass, a1, a2, TRUE);
2026 }
2027 
2028 /* --- */
2029 
2030 /*
2031  * call-seq:
2032  *    num.real  ->  self
2033  *
2034  * Returns self.
2035  */
2036 static VALUE
numeric_real(VALUE self)2037 numeric_real(VALUE self)
2038 {
2039     return self;
2040 }
2041 
2042 /*
2043  * call-seq:
2044  *    num.imag       ->  0
2045  *    num.imaginary  ->  0
2046  *
2047  * Returns zero.
2048  */
2049 static VALUE
numeric_imag(VALUE self)2050 numeric_imag(VALUE self)
2051 {
2052     return INT2FIX(0);
2053 }
2054 
2055 /*
2056  * call-seq:
2057  *    num.abs2  ->  real
2058  *
2059  * Returns square of self.
2060  */
2061 static VALUE
numeric_abs2(VALUE self)2062 numeric_abs2(VALUE self)
2063 {
2064     return f_mul(self, self);
2065 }
2066 
2067 /*
2068  * call-seq:
2069  *    num.arg    ->  0 or float
2070  *    num.angle  ->  0 or float
2071  *    num.phase  ->  0 or float
2072  *
2073  * Returns 0 if the value is positive, pi otherwise.
2074  */
2075 static VALUE
numeric_arg(VALUE self)2076 numeric_arg(VALUE self)
2077 {
2078     if (f_positive_p(self))
2079         return INT2FIX(0);
2080     return DBL2NUM(M_PI);
2081 }
2082 
2083 /*
2084  * call-seq:
2085  *    num.rect  ->  array
2086  *    num.rectangular  ->  array
2087  *
2088  * Returns an array; [num, 0].
2089  */
2090 static VALUE
numeric_rect(VALUE self)2091 numeric_rect(VALUE self)
2092 {
2093     return rb_assoc_new(self, INT2FIX(0));
2094 }
2095 
2096 static VALUE float_arg(VALUE self);
2097 
2098 /*
2099  * call-seq:
2100  *    num.polar  ->  array
2101  *
2102  * Returns an array; [num.abs, num.arg].
2103  */
2104 static VALUE
numeric_polar(VALUE self)2105 numeric_polar(VALUE self)
2106 {
2107     VALUE abs, arg;
2108 
2109     if (RB_INTEGER_TYPE_P(self)) {
2110         abs = rb_int_abs(self);
2111         arg = numeric_arg(self);
2112     }
2113     else if (RB_FLOAT_TYPE_P(self)) {
2114         abs = rb_float_abs(self);
2115         arg = float_arg(self);
2116     }
2117     else if (RB_TYPE_P(self, T_RATIONAL)) {
2118         abs = rb_rational_abs(self);
2119         arg = numeric_arg(self);
2120     }
2121     else {
2122         abs = f_abs(self);
2123         arg = f_arg(self);
2124     }
2125     return rb_assoc_new(abs, arg);
2126 }
2127 
2128 /*
2129  * call-seq:
2130  *    num.conj       ->  self
2131  *    num.conjugate  ->  self
2132  *
2133  * Returns self.
2134  */
2135 static VALUE
numeric_conj(VALUE self)2136 numeric_conj(VALUE self)
2137 {
2138     return self;
2139 }
2140 
2141 /*
2142  * call-seq:
2143  *    flo.arg    ->  0 or float
2144  *    flo.angle  ->  0 or float
2145  *    flo.phase  ->  0 or float
2146  *
2147  * Returns 0 if the value is positive, pi otherwise.
2148  */
2149 static VALUE
float_arg(VALUE self)2150 float_arg(VALUE self)
2151 {
2152     if (isnan(RFLOAT_VALUE(self)))
2153 	return self;
2154     if (f_tpositive_p(self))
2155 	return INT2FIX(0);
2156     return rb_const_get(rb_mMath, id_PI);
2157 }
2158 
2159 /*
2160  * A complex number can be represented as a paired real number with
2161  * imaginary unit; a+bi.  Where a is real part, b is imaginary part
2162  * and i is imaginary unit.  Real a equals complex a+0i
2163  * mathematically.
2164  *
2165  * Complex object can be created as literal, and also by using
2166  * Kernel#Complex, Complex::rect, Complex::polar or to_c method.
2167  *
2168  *    2+1i                 #=> (2+1i)
2169  *    Complex(1)           #=> (1+0i)
2170  *    Complex(2, 3)        #=> (2+3i)
2171  *    Complex.polar(2, 3)  #=> (-1.9799849932008908+0.2822400161197344i)
2172  *    3.to_c               #=> (3+0i)
2173  *
2174  * You can also create complex object from floating-point numbers or
2175  * strings.
2176  *
2177  *    Complex(0.3)         #=> (0.3+0i)
2178  *    Complex('0.3-0.5i')  #=> (0.3-0.5i)
2179  *    Complex('2/3+3/4i')  #=> ((2/3)+(3/4)*i)
2180  *    Complex('1@2')       #=> (-0.4161468365471424+0.9092974268256817i)
2181  *
2182  *    0.3.to_c             #=> (0.3+0i)
2183  *    '0.3-0.5i'.to_c      #=> (0.3-0.5i)
2184  *    '2/3+3/4i'.to_c      #=> ((2/3)+(3/4)*i)
2185  *    '1@2'.to_c           #=> (-0.4161468365471424+0.9092974268256817i)
2186  *
2187  * A complex object is either an exact or an inexact number.
2188  *
2189  *    Complex(1, 1) / 2    #=> ((1/2)+(1/2)*i)
2190  *    Complex(1, 1) / 2.0  #=> (0.5+0.5i)
2191  */
2192 void
Init_Complex(void)2193 Init_Complex(void)
2194 {
2195     VALUE compat;
2196 #undef rb_intern
2197 #define rb_intern(str) rb_intern_const(str)
2198 
2199     id_abs = rb_intern("abs");
2200     id_arg = rb_intern("arg");
2201     id_denominator = rb_intern("denominator");
2202     id_fdiv = rb_intern("fdiv");
2203     id_numerator = rb_intern("numerator");
2204     id_quo = rb_intern("quo");
2205     id_real_p = rb_intern("real?");
2206     id_i_real = rb_intern("@real");
2207     id_i_imag = rb_intern("@image"); /* @image, not @imag */
2208     id_finite_p = rb_intern("finite?");
2209     id_infinite_p = rb_intern("infinite?");
2210     id_rationalize = rb_intern("rationalize");
2211     id_PI = rb_intern("PI");
2212 
2213     rb_cComplex = rb_define_class("Complex", rb_cNumeric);
2214 
2215     rb_define_alloc_func(rb_cComplex, nucomp_s_alloc);
2216     rb_undef_method(CLASS_OF(rb_cComplex), "allocate");
2217 
2218     rb_undef_method(CLASS_OF(rb_cComplex), "new");
2219 
2220     rb_define_singleton_method(rb_cComplex, "rectangular", nucomp_s_new, -1);
2221     rb_define_singleton_method(rb_cComplex, "rect", nucomp_s_new, -1);
2222     rb_define_singleton_method(rb_cComplex, "polar", nucomp_s_polar, -1);
2223 
2224     rb_define_global_function("Complex", nucomp_f_complex, -1);
2225 
2226     rb_undef_methods_from(rb_cComplex, rb_mComparable);
2227     rb_undef_method(rb_cComplex, "%");
2228     rb_undef_method(rb_cComplex, "<=>");
2229     rb_undef_method(rb_cComplex, "div");
2230     rb_undef_method(rb_cComplex, "divmod");
2231     rb_undef_method(rb_cComplex, "floor");
2232     rb_undef_method(rb_cComplex, "ceil");
2233     rb_undef_method(rb_cComplex, "modulo");
2234     rb_undef_method(rb_cComplex, "remainder");
2235     rb_undef_method(rb_cComplex, "round");
2236     rb_undef_method(rb_cComplex, "step");
2237     rb_undef_method(rb_cComplex, "truncate");
2238     rb_undef_method(rb_cComplex, "i");
2239 
2240     rb_define_method(rb_cComplex, "real", rb_complex_real, 0);
2241     rb_define_method(rb_cComplex, "imaginary", rb_complex_imag, 0);
2242     rb_define_method(rb_cComplex, "imag", rb_complex_imag, 0);
2243 
2244     rb_define_method(rb_cComplex, "-@", rb_complex_uminus, 0);
2245     rb_define_method(rb_cComplex, "+", rb_complex_plus, 1);
2246     rb_define_method(rb_cComplex, "-", rb_complex_minus, 1);
2247     rb_define_method(rb_cComplex, "*", rb_complex_mul, 1);
2248     rb_define_method(rb_cComplex, "/", rb_complex_div, 1);
2249     rb_define_method(rb_cComplex, "quo", nucomp_quo, 1);
2250     rb_define_method(rb_cComplex, "fdiv", nucomp_fdiv, 1);
2251     rb_define_method(rb_cComplex, "**", rb_complex_pow, 1);
2252 
2253     rb_define_method(rb_cComplex, "==", nucomp_eqeq_p, 1);
2254     rb_define_method(rb_cComplex, "coerce", nucomp_coerce, 1);
2255 
2256     rb_define_method(rb_cComplex, "abs", rb_complex_abs, 0);
2257     rb_define_method(rb_cComplex, "magnitude", rb_complex_abs, 0);
2258     rb_define_method(rb_cComplex, "abs2", nucomp_abs2, 0);
2259     rb_define_method(rb_cComplex, "arg", rb_complex_arg, 0);
2260     rb_define_method(rb_cComplex, "angle", rb_complex_arg, 0);
2261     rb_define_method(rb_cComplex, "phase", rb_complex_arg, 0);
2262     rb_define_method(rb_cComplex, "rectangular", nucomp_rect, 0);
2263     rb_define_method(rb_cComplex, "rect", nucomp_rect, 0);
2264     rb_define_method(rb_cComplex, "polar", nucomp_polar, 0);
2265     rb_define_method(rb_cComplex, "conjugate", rb_complex_conjugate, 0);
2266     rb_define_method(rb_cComplex, "conj", rb_complex_conjugate, 0);
2267 
2268     rb_define_method(rb_cComplex, "real?", nucomp_false, 0);
2269 
2270     rb_define_method(rb_cComplex, "numerator", nucomp_numerator, 0);
2271     rb_define_method(rb_cComplex, "denominator", nucomp_denominator, 0);
2272 
2273     rb_define_method(rb_cComplex, "hash", nucomp_hash, 0);
2274     rb_define_method(rb_cComplex, "eql?", nucomp_eql_p, 1);
2275 
2276     rb_define_method(rb_cComplex, "to_s", nucomp_to_s, 0);
2277     rb_define_method(rb_cComplex, "inspect", nucomp_inspect, 0);
2278 
2279     rb_undef_method(rb_cComplex, "positive?");
2280     rb_undef_method(rb_cComplex, "negative?");
2281 
2282     rb_define_method(rb_cComplex, "finite?", rb_complex_finite_p, 0);
2283     rb_define_method(rb_cComplex, "infinite?", rb_complex_infinite_p, 0);
2284 
2285     rb_define_private_method(rb_cComplex, "marshal_dump", nucomp_marshal_dump, 0);
2286     /* :nodoc: */
2287     compat = rb_define_class_under(rb_cComplex, "compatible", rb_cObject);
2288     rb_define_private_method(compat, "marshal_load", nucomp_marshal_load, 1);
2289     rb_marshal_define_compat(rb_cComplex, compat, nucomp_dumper, nucomp_loader);
2290 
2291     /* --- */
2292 
2293     rb_define_method(rb_cComplex, "to_i", nucomp_to_i, 0);
2294     rb_define_method(rb_cComplex, "to_f", nucomp_to_f, 0);
2295     rb_define_method(rb_cComplex, "to_r", nucomp_to_r, 0);
2296     rb_define_method(rb_cComplex, "rationalize", nucomp_rationalize, -1);
2297     rb_define_method(rb_cComplex, "to_c", nucomp_to_c, 0);
2298     rb_define_method(rb_cNilClass, "to_c", nilclass_to_c, 0);
2299     rb_define_method(rb_cNumeric, "to_c", numeric_to_c, 0);
2300 
2301     rb_define_method(rb_cString, "to_c", string_to_c, 0);
2302 
2303     rb_define_private_method(CLASS_OF(rb_cComplex), "convert", nucomp_s_convert, -1);
2304 
2305     /* --- */
2306 
2307     rb_define_method(rb_cNumeric, "real", numeric_real, 0);
2308     rb_define_method(rb_cNumeric, "imaginary", numeric_imag, 0);
2309     rb_define_method(rb_cNumeric, "imag", numeric_imag, 0);
2310     rb_define_method(rb_cNumeric, "abs2", numeric_abs2, 0);
2311     rb_define_method(rb_cNumeric, "arg", numeric_arg, 0);
2312     rb_define_method(rb_cNumeric, "angle", numeric_arg, 0);
2313     rb_define_method(rb_cNumeric, "phase", numeric_arg, 0);
2314     rb_define_method(rb_cNumeric, "rectangular", numeric_rect, 0);
2315     rb_define_method(rb_cNumeric, "rect", numeric_rect, 0);
2316     rb_define_method(rb_cNumeric, "polar", numeric_polar, 0);
2317     rb_define_method(rb_cNumeric, "conjugate", numeric_conj, 0);
2318     rb_define_method(rb_cNumeric, "conj", numeric_conj, 0);
2319 
2320     rb_define_method(rb_cFloat, "arg", float_arg, 0);
2321     rb_define_method(rb_cFloat, "angle", float_arg, 0);
2322     rb_define_method(rb_cFloat, "phase", float_arg, 0);
2323 
2324     /*
2325      * The imaginary unit.
2326      */
2327     rb_define_const(rb_cComplex, "I",
2328 		    f_complex_new_bang2(rb_cComplex, ZERO, ONE));
2329 
2330 #if !USE_FLONUM
2331     rb_gc_register_mark_object(RFLOAT_0 = DBL2NUM(0.0));
2332 #endif
2333 
2334     rb_provide("complex.so");	/* for backward compatibility */
2335 }
2336 
2337 /*
2338 Local variables:
2339 c-file-style: "ruby"
2340 End:
2341 */
2342