Ruby 4.1.0dev (2026-05-14 revision 4c3de1a7b063c91015a54b8b125676b60d565959)
complex.c (4c3de1a7b063c91015a54b8b125676b60d565959)
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/internal/config.h"
9
10#if defined _MSC_VER
11/* Microsoft Visual C does not define M_PI and others by default */
12# define _USE_MATH_DEFINES 1
13#endif
14
15#include <ctype.h>
16#include <math.h>
17
18#include "id.h"
19#include "internal.h"
20#include "internal/array.h"
21#include "internal/class.h"
22#include "internal/complex.h"
23#include "internal/error.h"
24#include "internal/math.h"
25#include "internal/numeric.h"
26#include "internal/object.h"
27#include "internal/rational.h"
28#include "internal/string.h"
29#include "ruby_assert.h"
30
31#define ZERO INT2FIX(0)
32#define ONE INT2FIX(1)
33#define TWO INT2FIX(2)
34#if USE_FLONUM
35#define RFLOAT_0 DBL2NUM(0)
36#else
37static VALUE RFLOAT_0;
38#endif
39
41
42static ID id_abs, id_arg,
43 id_denominator, id_numerator,
44 id_real_p, id_i_real, id_i_imag,
45 id_finite_p, id_infinite_p, id_rationalize,
46 id_PI;
47#define id_to_i idTo_i
48#define id_to_r idTo_r
49#define id_negate idUMinus
50#define id_expt idPow
51#define id_to_f idTo_f
52#define id_quo idQuo
53#define id_fdiv idFdiv
54
55#define PRESERVE_SIGNEDZERO
56
57inline static VALUE
58f_add(VALUE x, VALUE y)
59{
60 if (RB_INTEGER_TYPE_P(x) &&
61 LIKELY(rb_method_basic_definition_p(rb_cInteger, idPLUS))) {
62 if (FIXNUM_ZERO_P(x))
63 return y;
64 if (FIXNUM_ZERO_P(y))
65 return x;
66 return rb_int_plus(x, y);
67 }
68 else if (RB_FLOAT_TYPE_P(x) &&
69 LIKELY(rb_method_basic_definition_p(rb_cFloat, idPLUS))) {
70 if (FIXNUM_ZERO_P(y))
71 return x;
72 return rb_float_plus(x, y);
73 }
74 else if (RB_TYPE_P(x, T_RATIONAL) &&
75 LIKELY(rb_method_basic_definition_p(rb_cRational, idPLUS))) {
76 if (FIXNUM_ZERO_P(y))
77 return x;
78 return rb_rational_plus(x, y);
79 }
80
81 return rb_funcall(x, '+', 1, y);
82}
83
84inline static VALUE
85f_div(VALUE x, VALUE y)
86{
87 if (FIXNUM_P(y) && FIX2LONG(y) == 1)
88 return x;
89 return rb_funcall(x, '/', 1, y);
90}
91
92inline static int
93f_gt_p(VALUE x, VALUE y)
94{
95 if (RB_INTEGER_TYPE_P(x)) {
96 if (FIXNUM_P(x) && FIXNUM_P(y))
97 return (SIGNED_VALUE)x > (SIGNED_VALUE)y;
98 return RTEST(rb_int_gt(x, y));
99 }
100 else if (RB_FLOAT_TYPE_P(x))
101 return RTEST(rb_float_gt(x, y));
102 else if (RB_TYPE_P(x, T_RATIONAL)) {
103 int const cmp = rb_cmpint(rb_rational_cmp(x, y), x, y);
104 return cmp > 0;
105 }
106 return RTEST(rb_funcall(x, '>', 1, y));
107}
108
109inline static VALUE
110f_mul(VALUE x, VALUE y)
111{
112 if (RB_INTEGER_TYPE_P(x) &&
113 LIKELY(rb_method_basic_definition_p(rb_cInteger, idMULT))) {
114 if (FIXNUM_ZERO_P(y))
115 return ZERO;
116 if (FIXNUM_ZERO_P(x) && RB_INTEGER_TYPE_P(y))
117 return ZERO;
118 if (x == ONE) return y;
119 if (y == ONE) return x;
120 return rb_int_mul(x, y);
121 }
122 else if (RB_FLOAT_TYPE_P(x) &&
123 LIKELY(rb_method_basic_definition_p(rb_cFloat, idMULT))) {
124 if (y == ONE) return x;
125 return rb_float_mul(x, y);
126 }
127 else if (RB_TYPE_P(x, T_RATIONAL) &&
128 LIKELY(rb_method_basic_definition_p(rb_cRational, idMULT))) {
129 if (y == ONE) return x;
130 return rb_rational_mul(x, y);
131 }
132 else if (LIKELY(rb_method_basic_definition_p(CLASS_OF(x), idMULT))) {
133 if (y == ONE) return x;
134 }
135 return rb_funcall(x, '*', 1, y);
136}
137
138inline static VALUE
139f_sub(VALUE x, VALUE y)
140{
141 if (FIXNUM_ZERO_P(y) &&
142 LIKELY(rb_method_basic_definition_p(CLASS_OF(x), idMINUS))) {
143 return x;
144 }
145 return rb_funcall(x, '-', 1, y);
146}
147
148inline static VALUE
149f_abs(VALUE x)
150{
151 if (RB_INTEGER_TYPE_P(x)) {
152 return rb_int_abs(x);
153 }
154 else if (RB_FLOAT_TYPE_P(x)) {
155 return rb_float_abs(x);
156 }
157 else if (RB_TYPE_P(x, T_RATIONAL)) {
158 return rb_rational_abs(x);
159 }
160 else if (RB_TYPE_P(x, T_COMPLEX)) {
161 return rb_complex_abs(x);
162 }
163 return rb_funcall(x, id_abs, 0);
164}
165
166static VALUE numeric_arg(VALUE self);
167static VALUE float_arg(VALUE self);
168
169inline static VALUE
170f_arg(VALUE x)
171{
172 if (RB_INTEGER_TYPE_P(x)) {
173 return numeric_arg(x);
174 }
175 else if (RB_FLOAT_TYPE_P(x)) {
176 return float_arg(x);
177 }
178 else if (RB_TYPE_P(x, T_RATIONAL)) {
179 return numeric_arg(x);
180 }
181 else if (RB_TYPE_P(x, T_COMPLEX)) {
182 return rb_complex_arg(x);
183 }
184 return rb_funcall(x, id_arg, 0);
185}
186
187inline static VALUE
188f_numerator(VALUE x)
189{
190 if (RB_TYPE_P(x, T_RATIONAL)) {
191 return RRATIONAL(x)->num;
192 }
193 if (RB_FLOAT_TYPE_P(x)) {
194 return rb_float_numerator(x);
195 }
196 return x;
197}
198
199inline static VALUE
200f_denominator(VALUE x)
201{
202 if (RB_TYPE_P(x, T_RATIONAL)) {
203 return RRATIONAL(x)->den;
204 }
205 if (RB_FLOAT_TYPE_P(x)) {
206 return rb_float_denominator(x);
207 }
208 return INT2FIX(1);
209}
210
211inline static VALUE
212f_negate(VALUE x)
213{
214 if (RB_INTEGER_TYPE_P(x)) {
215 return rb_int_uminus(x);
216 }
217 else if (RB_FLOAT_TYPE_P(x)) {
218 return rb_float_uminus(x);
219 }
220 else if (RB_TYPE_P(x, T_RATIONAL)) {
221 return rb_rational_uminus(x);
222 }
223 else if (RB_TYPE_P(x, T_COMPLEX)) {
224 return rb_complex_uminus(x);
225 }
226 return rb_funcall(x, id_negate, 0);
227}
228
229static bool nucomp_real_p(VALUE self);
230
231static inline bool
232f_real_p(VALUE x)
233{
234 if (RB_INTEGER_TYPE_P(x)) {
235 return true;
236 }
237 else if (RB_FLOAT_TYPE_P(x)) {
238 return true;
239 }
240 else if (RB_TYPE_P(x, T_RATIONAL)) {
241 return true;
242 }
243 else if (RB_TYPE_P(x, T_COMPLEX)) {
244 return nucomp_real_p(x);
245 }
246 return rb_funcall(x, id_real_p, 0);
247}
248
249inline static VALUE
250f_to_i(VALUE x)
251{
252 if (RB_TYPE_P(x, T_STRING))
253 return rb_str_to_inum(x, 10, 0);
254 return rb_funcall(x, id_to_i, 0);
255}
256
257inline static VALUE
258f_to_f(VALUE x)
259{
260 if (RB_TYPE_P(x, T_STRING))
261 return DBL2NUM(rb_str_to_dbl(x, 0));
262 return rb_funcall(x, id_to_f, 0);
263}
264
265inline static int
266f_eqeq_p(VALUE x, VALUE y)
267{
268 if (FIXNUM_P(x) && FIXNUM_P(y))
269 return x == y;
270 else if (RB_FLOAT_TYPE_P(x) || RB_FLOAT_TYPE_P(y))
271 return NUM2DBL(x) == NUM2DBL(y);
272 return (int)rb_equal(x, y);
273}
274
275static VALUE
276f_fdiv(VALUE x, VALUE y)
277{
278 if (RB_INTEGER_TYPE_P(x))
279 return rb_int_fdiv(x, y);
280 if (RB_FLOAT_TYPE_P(x))
281 return rb_float_div(x, y);
282 if (RB_TYPE_P(x, T_RATIONAL))
283 return rb_rational_fdiv(x, y);
284
285 return rb_funcallv(x, id_fdiv, 1, &y);
286}
287
288static VALUE
289f_quo(VALUE x, VALUE y)
290{
291 if (RB_INTEGER_TYPE_P(x))
292 return rb_numeric_quo(x, y);
293 if (RB_FLOAT_TYPE_P(x))
294 return rb_float_div(x, y);
295 if (RB_TYPE_P(x, T_RATIONAL))
296 return rb_numeric_quo(x, y);
297
298 return rb_funcallv(x, id_quo, 1, &y);
299}
300
301inline static int
302f_negative_p(VALUE x)
303{
304 if (RB_INTEGER_TYPE_P(x))
305 return INT_NEGATIVE_P(x);
306 else if (RB_FLOAT_TYPE_P(x))
307 return RFLOAT_VALUE(x) < 0.0;
308 else if (RB_TYPE_P(x, T_RATIONAL))
309 return INT_NEGATIVE_P(RRATIONAL(x)->num);
310 return rb_num_negative_p(x);
311}
312
313#define f_positive_p(x) (!f_negative_p(x))
314
315static inline bool
316always_finite_type_p(VALUE x)
317{
318 if (FIXNUM_P(x)) return true;
319 if (FLONUM_P(x)) return true; /* Infinity can't be a flonum */
320 return (RB_INTEGER_TYPE_P(x) || RB_TYPE_P(x, T_RATIONAL));
321}
322
323inline static int
324f_finite_p(VALUE x)
325{
326 if (always_finite_type_p(x)) {
327 return TRUE;
328 }
329 else if (RB_FLOAT_TYPE_P(x)) {
330 return isfinite(RFLOAT_VALUE(x));
331 }
332 return RTEST(rb_funcallv(x, id_finite_p, 0, 0));
333}
334
335inline static int
336f_infinite_p(VALUE x)
337{
338 if (always_finite_type_p(x)) {
339 return FALSE;
340 }
341 else if (RB_FLOAT_TYPE_P(x)) {
342 return isinf(RFLOAT_VALUE(x));
343 }
344 return RTEST(rb_funcallv(x, id_infinite_p, 0, 0));
345}
346
347inline static int
348f_kind_of_p(VALUE x, VALUE c)
349{
350 return (int)rb_obj_is_kind_of(x, c);
351}
352
353inline static int
354k_numeric_p(VALUE x)
355{
356 return f_kind_of_p(x, rb_cNumeric);
357}
358
359#define k_exact_p(x) (!RB_FLOAT_TYPE_P(x))
360
361#define k_exact_zero_p(x) (k_exact_p(x) && f_zero_p(x))
362
363#define get_dat1(x) \
364 struct RComplex *dat = RCOMPLEX(x)
365
366#define get_dat2(x,y) \
367 struct RComplex *adat = RCOMPLEX(x), *bdat = RCOMPLEX(y)
368
369inline static VALUE
370nucomp_s_new_internal(VALUE klass, VALUE real, VALUE imag)
371{
372 NEWOBJ_OF(obj, struct RComplex, klass, T_COMPLEX, sizeof(struct RComplex));
373
374 RCOMPLEX_SET_REAL(obj, real);
375 RCOMPLEX_SET_IMAG(obj, imag);
376 OBJ_FREEZE((VALUE)obj);
377
378 return (VALUE)obj;
379}
380
381static VALUE
382nucomp_s_alloc(VALUE klass)
383{
384 return nucomp_s_new_internal(klass, ZERO, ZERO);
385}
386
387inline static VALUE
388f_complex_new_bang1(VALUE klass, VALUE x)
389{
391 return nucomp_s_new_internal(klass, x, ZERO);
392}
393
394inline static VALUE
395f_complex_new_bang2(VALUE klass, VALUE x, VALUE y)
396{
399 return nucomp_s_new_internal(klass, x, y);
400}
401
402WARN_UNUSED_RESULT(inline static VALUE nucomp_real_check(VALUE num));
403inline static VALUE
404nucomp_real_check(VALUE num)
405{
406 if (!RB_INTEGER_TYPE_P(num) &&
407 !RB_FLOAT_TYPE_P(num) &&
408 !RB_TYPE_P(num, T_RATIONAL)) {
409 if (RB_TYPE_P(num, T_COMPLEX) && nucomp_real_p(num)) {
410 VALUE real = RCOMPLEX(num)->real;
412 return real;
413 }
414 if (!k_numeric_p(num) || !f_real_p(num))
415 rb_raise(rb_eTypeError, "not a real");
416 }
417 return num;
418}
419
420inline static VALUE
421nucomp_s_canonicalize_internal(VALUE klass, VALUE real, VALUE imag)
422{
423 int complex_r, complex_i;
424 complex_r = RB_TYPE_P(real, T_COMPLEX);
425 complex_i = RB_TYPE_P(imag, T_COMPLEX);
426 if (!complex_r && !complex_i) {
427 return nucomp_s_new_internal(klass, real, imag);
428 }
429 else if (!complex_r) {
430 get_dat1(imag);
431
432 return nucomp_s_new_internal(klass,
433 f_sub(real, dat->imag),
434 f_add(ZERO, dat->real));
435 }
436 else if (!complex_i) {
437 get_dat1(real);
438
439 return nucomp_s_new_internal(klass,
440 dat->real,
441 f_add(dat->imag, imag));
442 }
443 else {
444 get_dat2(real, imag);
445
446 return nucomp_s_new_internal(klass,
447 f_sub(adat->real, bdat->imag),
448 f_add(adat->imag, bdat->real));
449 }
450}
451
452/*
453 * call-seq:
454 * Complex.rect(real, imag = 0) -> complex
455 *
456 * Returns a new \Complex object formed from the arguments,
457 * each of which must be an instance of Numeric,
458 * or an instance of one of its subclasses:
459 * \Complex, Float, Integer, Rational;
460 * see {Rectangular Coordinates}[rdoc-ref:Complex@Rectangular+Coordinates]:
461 *
462 * Complex.rect(3) # => (3+0i)
463 * Complex.rect(3, Math::PI) # => (3+3.141592653589793i)
464 * Complex.rect(-3, -Math::PI) # => (-3-3.141592653589793i)
465 *
466 * \Complex.rectangular is an alias for \Complex.rect.
467 */
468static VALUE
469nucomp_s_new(int argc, VALUE *argv, VALUE klass)
470{
471 VALUE real, imag;
472
473 switch (rb_scan_args(argc, argv, "11", &real, &imag)) {
474 case 1:
475 real = nucomp_real_check(real);
476 imag = ZERO;
477 break;
478 default:
479 real = nucomp_real_check(real);
480 imag = nucomp_real_check(imag);
481 break;
482 }
483
484 return nucomp_s_new_internal(klass, real, imag);
485}
486
487inline static VALUE
488f_complex_new2(VALUE klass, VALUE x, VALUE y)
489{
490 if (RB_TYPE_P(x, T_COMPLEX)) {
491 get_dat1(x);
492 x = dat->real;
493 y = f_add(dat->imag, y);
494 }
495 return nucomp_s_canonicalize_internal(klass, x, y);
496}
497
498static VALUE nucomp_convert(VALUE klass, VALUE a1, VALUE a2, int raise);
499static VALUE nucomp_s_convert(int argc, VALUE *argv, VALUE klass);
500
501/*
502 * call-seq:
503 * Complex(real, imag = 0, exception: true) -> complex or nil
504 * Complex(s, exception: true) -> complex or nil
505 *
506 * Returns a new \Complex object if the arguments are valid;
507 * otherwise raises an exception if +exception+ is +true+;
508 * otherwise returns +nil+.
509 *
510 * With Numeric arguments +real+ and +imag+,
511 * returns <tt>Complex.rect(real, imag)</tt> if the arguments are valid.
512 *
513 * With string argument +s+, returns a new \Complex object if the argument is valid;
514 * the string may have:
515 *
516 * - One or two numeric substrings,
517 * each of which specifies a Complex, Float, Integer, Numeric, or Rational value,
518 * specifying {rectangular coordinates}[rdoc-ref:Complex@Rectangular+Coordinates]:
519 *
520 * - Sign-separated real and imaginary numeric substrings
521 * (with trailing character <tt>'i'</tt>):
522 *
523 * Complex('1+2i') # => (1+2i)
524 * Complex('+1+2i') # => (1+2i)
525 * Complex('+1-2i') # => (1-2i)
526 * Complex('-1+2i') # => (-1+2i)
527 * Complex('-1-2i') # => (-1-2i)
528 *
529 * - Real-only numeric string (without trailing character <tt>'i'</tt>):
530 *
531 * Complex('1') # => (1+0i)
532 * Complex('+1') # => (1+0i)
533 * Complex('-1') # => (-1+0i)
534 *
535 * - Imaginary-only numeric string (with trailing character <tt>'i'</tt>):
536 *
537 * Complex('1i') # => (0+1i)
538 * Complex('+1i') # => (0+1i)
539 * Complex('-1i') # => (0-1i)
540 *
541 * - At-sign separated real and imaginary rational substrings,
542 * each of which specifies a Rational value,
543 * specifying {polar coordinates}[rdoc-ref:Complex@Polar+Coordinates]:
544 *
545 * Complex('1/2@3/4') # => (0.36584443443691045+0.34081938001166706i)
546 * Complex('+1/2@+3/4') # => (0.36584443443691045+0.34081938001166706i)
547 * Complex('+1/2@-3/4') # => (0.36584443443691045-0.34081938001166706i)
548 * Complex('-1/2@+3/4') # => (-0.36584443443691045-0.34081938001166706i)
549 * Complex('-1/2@-3/4') # => (-0.36584443443691045+0.34081938001166706i)
550 *
551 */
552static VALUE
553nucomp_f_complex(int argc, VALUE *argv, VALUE klass)
554{
555 VALUE a1, a2, opts = Qnil;
556 int raise = TRUE;
557
558 if (rb_scan_args(argc, argv, "11:", &a1, &a2, &opts) == 1) {
559 a2 = Qundef;
560 }
561 if (!NIL_P(opts)) {
562 raise = rb_opts_exception_p(opts, raise);
563 }
564 if (argc > 0 && CLASS_OF(a1) == rb_cComplex && UNDEF_P(a2)) {
565 return a1;
566 }
567 return nucomp_convert(rb_cComplex, a1, a2, raise);
568}
569
570#define imp1(n) \
571inline static VALUE \
572m_##n##_bang(VALUE x)\
573{\
574 return rb_math_##n(x);\
575}
576
577imp1(cos)
578imp1(cosh)
579imp1(exp)
580
581static VALUE
582m_log_bang(VALUE x)
583{
584 return rb_math_log(1, &x);
585}
586
587imp1(sin)
588imp1(sinh)
589
590static VALUE
591m_cos(VALUE x)
592{
593 if (!RB_TYPE_P(x, T_COMPLEX))
594 return m_cos_bang(x);
595 {
596 get_dat1(x);
597 return f_complex_new2(rb_cComplex,
598 f_mul(m_cos_bang(dat->real),
599 m_cosh_bang(dat->imag)),
600 f_mul(f_negate(m_sin_bang(dat->real)),
601 m_sinh_bang(dat->imag)));
602 }
603}
604
605static VALUE
606m_sin(VALUE x)
607{
608 if (!RB_TYPE_P(x, T_COMPLEX))
609 return m_sin_bang(x);
610 {
611 get_dat1(x);
612 return f_complex_new2(rb_cComplex,
613 f_mul(m_sin_bang(dat->real),
614 m_cosh_bang(dat->imag)),
615 f_mul(m_cos_bang(dat->real),
616 m_sinh_bang(dat->imag)));
617 }
618}
619
620static VALUE
621f_complex_polar_real(VALUE klass, VALUE x, VALUE y)
622{
623 if (f_zero_p(x) || f_zero_p(y)) {
624 return nucomp_s_new_internal(klass, x, RFLOAT_0);
625 }
626 if (RB_FLOAT_TYPE_P(y)) {
627 const double arg = RFLOAT_VALUE(y);
628 if (arg == M_PI) {
629 x = f_negate(x);
630 y = RFLOAT_0;
631 }
632 else if (arg == M_PI_2) {
633 y = x;
634 x = RFLOAT_0;
635 }
636 else if (arg == M_PI_2+M_PI) {
637 y = f_negate(x);
638 x = RFLOAT_0;
639 }
640 else if (RB_FLOAT_TYPE_P(x)) {
641 const double abs = RFLOAT_VALUE(x);
642 const double real = abs * cos(arg), imag = abs * sin(arg);
643 x = DBL2NUM(real);
644 y = DBL2NUM(imag);
645 }
646 else {
647 const double ax = sin(arg), ay = cos(arg);
648 y = f_mul(x, DBL2NUM(ax));
649 x = f_mul(x, DBL2NUM(ay));
650 }
651 return nucomp_s_new_internal(klass, x, y);
652 }
653 return nucomp_s_canonicalize_internal(klass,
654 f_mul(x, m_cos(y)),
655 f_mul(x, m_sin(y)));
656}
657
658static VALUE
659f_complex_polar(VALUE klass, VALUE x, VALUE y)
660{
661 x = nucomp_real_check(x);
662 y = nucomp_real_check(y);
663 return f_complex_polar_real(klass, x, y);
664}
665
666#ifdef HAVE___COSPI
667# define cospi(x) __cospi(x)
668#else
669# define cospi(x) cos((x) * M_PI)
670#endif
671#ifdef HAVE___SINPI
672# define sinpi(x) __sinpi(x)
673#else
674# define sinpi(x) sin((x) * M_PI)
675#endif
676/* returns a Complex or Float of ang*PI-rotated abs */
677VALUE
678rb_dbl_complex_new_polar_pi(double abs, double ang)
679{
680 double fi;
681 const double fr = modf(ang, &fi);
682 int pos = fr == +0.5;
683
684 if (pos || fr == -0.5) {
685 if ((modf(fi / 2.0, &fi) != fr) ^ pos) abs = -abs;
686 return rb_complex_new(RFLOAT_0, DBL2NUM(abs));
687 }
688 else if (fr == 0.0) {
689 if (modf(fi / 2.0, &fi) != 0.0) abs = -abs;
690 return DBL2NUM(abs);
691 }
692 else {
693 const double real = abs * cospi(ang), imag = abs * sinpi(ang);
694 return rb_complex_new(DBL2NUM(real), DBL2NUM(imag));
695 }
696}
697
698/*
699 * call-seq:
700 * Complex.polar(abs, arg = 0) -> complex
701 *
702 * Returns a new \Complex object formed from the arguments,
703 * each of which must be an instance of Numeric,
704 * or an instance of one of its subclasses:
705 * \Complex, Float, Integer, Rational.
706 * Argument +arg+ is given in radians;
707 * see {Polar Coordinates}[rdoc-ref:Complex@Polar+Coordinates]:
708 *
709 * Complex.polar(3) # => (3+0i)
710 * Complex.polar(3, 2.0) # => (-1.2484405096414273+2.727892280477045i)
711 * Complex.polar(-3, -2.0) # => (1.2484405096414273+2.727892280477045i)
712 *
713 */
714static VALUE
715nucomp_s_polar(int argc, VALUE *argv, VALUE klass)
716{
717 VALUE abs, arg;
718
719 argc = rb_scan_args(argc, argv, "11", &abs, &arg);
720 abs = nucomp_real_check(abs);
721 if (argc == 2) {
722 arg = nucomp_real_check(arg);
723 }
724 else {
725 arg = ZERO;
726 }
727 return f_complex_polar_real(klass, abs, arg);
728}
729
730/*
731 * call-seq:
732 * real -> numeric
733 *
734 * Returns the real value for +self+:
735 *
736 * Complex.rect(7).real # => 7
737 * Complex.rect(9, -4).real # => 9
738 *
739 * If +self+ was created with
740 * {polar coordinates}[rdoc-ref:Complex@Polar+Coordinates], the returned value
741 * is computed, and may be inexact:
742 *
743 * Complex.polar(1, Math::PI/4).real # => 0.7071067811865476 # Square root of 2.
744 *
745 */
746VALUE
747rb_complex_real(VALUE self)
748{
749 get_dat1(self);
750 return dat->real;
751}
752
753/*
754 * call-seq:
755 * imag -> numeric
756 *
757 * Returns the imaginary value for +self+:
758 *
759 * Complex.rect(7).imag # => 0
760 * Complex.rect(9, -4).imag # => -4
761 *
762 * If +self+ was created with
763 * {polar coordinates}[rdoc-ref:Complex@Polar+Coordinates], the returned value
764 * is computed, and may be inexact:
765 *
766 * Complex.polar(1, Math::PI/4).imag # => 0.7071067811865476 # Square root of 2.
767 *
768 */
769VALUE
770rb_complex_imag(VALUE self)
771{
772 get_dat1(self);
773 return dat->imag;
774}
775
776/*
777 * call-seq:
778 * -self -> complex
779 *
780 * Returns +self+, negated, which is the negation of each of its parts:
781 *
782 * -Complex.rect(1, 2) # => (-1-2i)
783 * -Complex.rect(-1, -2) # => (1+2i)
784 *
785 */
786VALUE
787rb_complex_uminus(VALUE self)
788{
789 get_dat1(self);
790 return f_complex_new2(CLASS_OF(self),
791 f_negate(dat->real), f_negate(dat->imag));
792}
793
794/*
795 * call-seq:
796 * self + other -> numeric
797 *
798 * Returns the sum of +self+ and +other+:
799 *
800 * Complex(1, 2) + 0 # => (1+2i)
801 * Complex(1, 2) + 1 # => (2+2i)
802 * Complex(1, 2) + -1 # => (0+2i)
803 *
804 * Complex(1, 2) + 1.0 # => (2.0+2i)
805 *
806 * Complex(1, 2) + Complex(2, 1) # => (3+3i)
807 * Complex(1, 2) + Complex(2.0, 1.0) # => (3.0+3.0i)
808 *
809 * Complex(1, 2) + Rational(1, 1) # => ((2/1)+2i)
810 * Complex(1, 2) + Rational(1, 2) # => ((3/2)+2i)
811 *
812 * For a computation involving Floats, the result may be inexact (see Float#+):
813 *
814 * Complex(1, 2) + 3.14 # => (4.140000000000001+2i)
815 */
816VALUE
817rb_complex_plus(VALUE self, VALUE other)
818{
819 if (RB_TYPE_P(other, T_COMPLEX)) {
820 VALUE real, imag;
821
822 get_dat2(self, other);
823
824 real = f_add(adat->real, bdat->real);
825 imag = f_add(adat->imag, bdat->imag);
826
827 return f_complex_new2(CLASS_OF(self), real, imag);
828 }
829 if (k_numeric_p(other) && f_real_p(other)) {
830 get_dat1(self);
831
832 return f_complex_new2(CLASS_OF(self),
833 f_add(dat->real, other), dat->imag);
834 }
835 return rb_num_coerce_bin(self, other, '+');
836}
837
838/*
839 * call-seq:
840 * self - other -> complex
841 *
842 * Returns the difference of +self+ and +other+:
843 *
844 * Complex.rect(2, 3) - Complex.rect(2, 3) # => (0+0i)
845 * Complex.rect(900) - Complex.rect(1) # => (899+0i)
846 * Complex.rect(-2, 9) - Complex.rect(-9, 2) # => (7+7i)
847 * Complex.rect(9, 8) - 4 # => (5+8i)
848 * Complex.rect(20, 9) - 9.8 # => (10.2+9i)
849 *
850 */
851VALUE
852rb_complex_minus(VALUE self, VALUE other)
853{
854 if (RB_TYPE_P(other, T_COMPLEX)) {
855 VALUE real, imag;
856
857 get_dat2(self, other);
858
859 real = f_sub(adat->real, bdat->real);
860 imag = f_sub(adat->imag, bdat->imag);
861
862 return f_complex_new2(CLASS_OF(self), real, imag);
863 }
864 if (k_numeric_p(other) && f_real_p(other)) {
865 get_dat1(self);
866
867 return f_complex_new2(CLASS_OF(self),
868 f_sub(dat->real, other), dat->imag);
869 }
870 return rb_num_coerce_bin(self, other, '-');
871}
872
873static VALUE
874safe_mul(VALUE a, VALUE b, bool az, bool bz)
875{
876 double v;
877 if (!az && bz && RB_FLOAT_TYPE_P(a) && (v = RFLOAT_VALUE(a), !isnan(v))) {
878 a = signbit(v) ? DBL2NUM(-1.0) : DBL2NUM(1.0);
879 }
880 if (!bz && az && RB_FLOAT_TYPE_P(b) && (v = RFLOAT_VALUE(b), !isnan(v))) {
881 b = signbit(v) ? DBL2NUM(-1.0) : DBL2NUM(1.0);
882 }
883 return f_mul(a, b);
884}
885
886static void
887comp_mul(VALUE areal, VALUE aimag, VALUE breal, VALUE bimag, VALUE *real, VALUE *imag)
888{
889 bool arzero = f_zero_p(areal);
890 bool aizero = f_zero_p(aimag);
891 bool brzero = f_zero_p(breal);
892 bool bizero = f_zero_p(bimag);
893 *real = f_sub(safe_mul(areal, breal, arzero, brzero),
894 safe_mul(aimag, bimag, aizero, bizero));
895 *imag = f_add(safe_mul(areal, bimag, arzero, bizero),
896 safe_mul(aimag, breal, aizero, brzero));
897}
898
899/*
900 * call-seq:
901 * self * other -> numeric
902 *
903 * Returns the numeric product of +self+ and +other+:
904 *
905 * Complex.rect(9, 8) * 4 # => (36+32i)
906 * Complex.rect(20, 9) * 9.8 # => (196.0+88.2i)
907 * Complex.rect(2, 3) * Complex.rect(2, 3) # => (-5+12i)
908 * Complex.rect(900) * Complex.rect(1) # => (900+0i)
909 * Complex.rect(-2, 9) * Complex.rect(-9, 2) # => (0-85i)
910 * Complex.rect(9, 8) * Rational(2, 3) # => ((6/1)+(16/3)*i)
911 *
912 */
913VALUE
914rb_complex_mul(VALUE self, VALUE other)
915{
916 if (RB_TYPE_P(other, T_COMPLEX)) {
917 VALUE real, imag;
918 get_dat2(self, other);
919
920 comp_mul(adat->real, adat->imag, bdat->real, bdat->imag, &real, &imag);
921
922 return f_complex_new2(CLASS_OF(self), real, imag);
923 }
924 if (k_numeric_p(other) && f_real_p(other)) {
925 get_dat1(self);
926
927 return f_complex_new2(CLASS_OF(self),
928 f_mul(dat->real, other),
929 f_mul(dat->imag, other));
930 }
931 return rb_num_coerce_bin(self, other, '*');
932}
933
934inline static VALUE
935f_divide(VALUE self, VALUE other,
936 VALUE (*func)(VALUE, VALUE), ID id)
937{
938 if (RB_TYPE_P(other, T_COMPLEX)) {
939 VALUE r, n, x, y;
940 int flo;
941 get_dat2(self, other);
942
943 flo = (RB_FLOAT_TYPE_P(adat->real) || RB_FLOAT_TYPE_P(adat->imag) ||
944 RB_FLOAT_TYPE_P(bdat->real) || RB_FLOAT_TYPE_P(bdat->imag));
945
946 if (f_gt_p(f_abs(bdat->real), f_abs(bdat->imag))) {
947 r = (*func)(bdat->imag, bdat->real);
948 n = f_mul(bdat->real, f_add(ONE, f_mul(r, r)));
949 x = (*func)(f_add(adat->real, f_mul(adat->imag, r)), n);
950 y = (*func)(f_sub(adat->imag, f_mul(adat->real, r)), n);
951 }
952 else {
953 r = (*func)(bdat->real, bdat->imag);
954 n = f_mul(bdat->imag, f_add(ONE, f_mul(r, r)));
955 x = (*func)(f_add(f_mul(adat->real, r), adat->imag), n);
956 y = (*func)(f_sub(f_mul(adat->imag, r), adat->real), n);
957 }
958 if (!flo) {
959 x = rb_rational_canonicalize(x);
960 y = rb_rational_canonicalize(y);
961 }
962 return f_complex_new2(CLASS_OF(self), x, y);
963 }
964 if (k_numeric_p(other) && f_real_p(other)) {
965 VALUE x, y;
966 get_dat1(self);
967 x = rb_rational_canonicalize((*func)(dat->real, other));
968 y = rb_rational_canonicalize((*func)(dat->imag, other));
969 return f_complex_new2(CLASS_OF(self), x, y);
970 }
971 return rb_num_coerce_bin(self, other, id);
972}
973
974#define rb_raise_zerodiv() rb_raise(rb_eZeroDivError, "divided by 0")
975
976/*
977 * call-seq:
978 * self / other -> complex
979 *
980 * Returns the quotient of +self+ and +other+:
981 *
982 * Complex.rect(2, 3) / Complex.rect(2, 3) # => (1+0i)
983 * Complex.rect(900) / Complex.rect(1) # => (900+0i)
984 * Complex.rect(-2, 9) / Complex.rect(-9, 2) # => ((36/85)-(77/85)*i)
985 * Complex.rect(9, 8) / 4 # => ((9/4)+2i)
986 * Complex.rect(20, 9) / 9.8 # => (2.0408163265306123+0.9183673469387754i)
987 *
988 */
989VALUE
990rb_complex_div(VALUE self, VALUE other)
991{
992 return f_divide(self, other, f_quo, id_quo);
993}
994
995#define nucomp_quo rb_complex_div
996
997/*
998 * call-seq:
999 * fdiv(numeric) -> new_complex
1000 *
1001 * Returns <tt>Complex.rect(self.real/numeric, self.imag/numeric)</tt>:
1002 *
1003 * Complex.rect(11, 22).fdiv(3) # => (3.6666666666666665+7.333333333333333i)
1004 *
1005 */
1006static VALUE
1007nucomp_fdiv(VALUE self, VALUE other)
1008{
1009 return f_divide(self, other, f_fdiv, id_fdiv);
1010}
1011
1012inline static VALUE
1013f_reciprocal(VALUE x)
1014{
1015 return f_quo(ONE, x);
1016}
1017
1018static VALUE
1019zero_for(VALUE x)
1020{
1021 if (RB_FLOAT_TYPE_P(x))
1022 return DBL2NUM(0);
1023 if (RB_TYPE_P(x, T_RATIONAL))
1024 return rb_rational_new(INT2FIX(0), INT2FIX(1));
1025
1026 return INT2FIX(0);
1027}
1028
1029static VALUE
1030complex_pow_for_special_angle(VALUE self, VALUE other)
1031{
1032 if (!rb_integer_type_p(other)) {
1033 return Qundef;
1034 }
1035
1036 get_dat1(self);
1037 VALUE x = Qundef;
1038 int dir;
1039 if (f_zero_p(dat->imag)) {
1040 x = dat->real;
1041 dir = 0;
1042 }
1043 else if (f_zero_p(dat->real)) {
1044 x = dat->imag;
1045 dir = 2;
1046 }
1047 else if (f_eqeq_p(dat->real, dat->imag)) {
1048 x = dat->real;
1049 dir = 1;
1050 }
1051 else if (f_eqeq_p(dat->real, f_negate(dat->imag))) {
1052 x = dat->imag;
1053 dir = 3;
1054 }
1055 else {
1056 dir = 0;
1057 }
1058
1059 if (UNDEF_P(x)) return x;
1060
1061 if (f_negative_p(x)) {
1062 x = f_negate(x);
1063 dir += 4;
1064 }
1065
1066 VALUE zx;
1067 if (dir % 2 == 0) {
1068 zx = rb_num_pow(x, other);
1069 }
1070 else {
1071 zx = rb_num_pow(
1072 rb_funcall(rb_int_mul(TWO, x), '*', 1, x),
1073 rb_int_div(other, TWO)
1074 );
1075 if (rb_int_odd_p(other)) {
1076 zx = rb_funcall(zx, '*', 1, x);
1077 }
1078 }
1079 static const int dirs[][2] = {
1080 {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}
1081 };
1082 int z_dir = FIX2INT(rb_int_modulo(rb_int_mul(INT2FIX(dir), other), INT2FIX(8)));
1083
1084 VALUE zr = Qfalse, zi = Qfalse;
1085 switch (dirs[z_dir][0]) {
1086 case 0: zr = zero_for(zx); break;
1087 case 1: zr = zx; break;
1088 case -1: zr = f_negate(zx); break;
1089 }
1090 switch (dirs[z_dir][1]) {
1091 case 0: zi = zero_for(zx); break;
1092 case 1: zi = zx; break;
1093 case -1: zi = f_negate(zx); break;
1094 }
1095 return nucomp_s_new_internal(CLASS_OF(self), zr, zi);
1096}
1097
1098
1099/*
1100 * call-seq:
1101 * self ** exponent -> complex
1102 *
1103 * Returns +self+ raised to the power +exponent+:
1104 *
1105 * Complex.rect(0, 1) ** 2 # => (-1+0i)
1106 * Complex.rect(-8) ** Rational(1, 3) # => (1.0000000000000002+1.7320508075688772i)
1107 *
1108 */
1109VALUE
1110rb_complex_pow(VALUE self, VALUE other)
1111{
1112 if (k_numeric_p(other) && k_exact_zero_p(other))
1113 return f_complex_new_bang1(CLASS_OF(self), ONE);
1114
1115 if (RB_TYPE_P(other, T_RATIONAL) && RRATIONAL(other)->den == LONG2FIX(1))
1116 other = RRATIONAL(other)->num; /* c14n */
1117
1118 if (RB_TYPE_P(other, T_COMPLEX)) {
1119 get_dat1(other);
1120
1121 if (k_exact_zero_p(dat->imag))
1122 other = dat->real; /* c14n */
1123 }
1124
1125 if (other == ONE) {
1126 get_dat1(self);
1127 return nucomp_s_new_internal(CLASS_OF(self), dat->real, dat->imag);
1128 }
1129
1130 VALUE result = complex_pow_for_special_angle(self, other);
1131 if (!UNDEF_P(result)) return result;
1132
1133 if (RB_TYPE_P(other, T_COMPLEX)) {
1134 VALUE r, theta, nr, ntheta;
1135
1136 get_dat1(other);
1137
1138 r = f_abs(self);
1139 theta = f_arg(self);
1140
1141 nr = m_exp_bang(f_sub(f_mul(dat->real, m_log_bang(r)),
1142 f_mul(dat->imag, theta)));
1143 ntheta = f_add(f_mul(theta, dat->real),
1144 f_mul(dat->imag, m_log_bang(r)));
1145 return f_complex_polar(CLASS_OF(self), nr, ntheta);
1146 }
1147 if (FIXNUM_P(other)) {
1148 long n = FIX2LONG(other);
1149 if (n == 0) {
1150 return nucomp_s_new_internal(CLASS_OF(self), ONE, ZERO);
1151 }
1152 if (n < 0) {
1153 self = f_reciprocal(self);
1154 other = rb_int_uminus(other);
1155 n = -n;
1156 }
1157 {
1158 get_dat1(self);
1159 VALUE xr = dat->real, xi = dat->imag, zr = xr, zi = xi;
1160
1161 if (f_zero_p(xi)) {
1162 zr = rb_num_pow(zr, other);
1163 }
1164 else if (f_zero_p(xr)) {
1165 zi = rb_num_pow(zi, other);
1166 if (n & 2) zi = f_negate(zi);
1167 if (!(n & 1)) {
1168 VALUE tmp = zr;
1169 zr = zi;
1170 zi = tmp;
1171 }
1172 }
1173 else {
1174 while (--n) {
1175 long q, r;
1176
1177 for (; q = n / 2, r = n % 2, r == 0; n = q) {
1178 VALUE tmp = f_sub(f_mul(xr, xr), f_mul(xi, xi));
1179 xi = f_mul(f_mul(TWO, xr), xi);
1180 xr = tmp;
1181 }
1182 comp_mul(zr, zi, xr, xi, &zr, &zi);
1183 }
1184 }
1185 return nucomp_s_new_internal(CLASS_OF(self), zr, zi);
1186 }
1187 }
1188 if (k_numeric_p(other) && f_real_p(other)) {
1189 VALUE r, theta;
1190
1191 if (RB_BIGNUM_TYPE_P(other))
1192 rb_warn("in a**b, b may be too big");
1193
1194 r = rb_num_pow(f_abs(self), other);
1195 theta = f_mul(f_arg(self), other);
1196
1197 return f_complex_polar(CLASS_OF(self), r, theta);
1198 }
1199 return rb_num_coerce_bin(self, other, id_expt);
1200}
1201
1202/*
1203 * call-seq:
1204 * self == other -> true or false
1205 *
1206 * Returns whether both <tt>self.real == other.real</tt>
1207 * and <tt>self.imag == other.imag</tt>:
1208 *
1209 * Complex.rect(2, 3) == Complex.rect(2.0, 3.0) # => true
1210 *
1211 */
1212static VALUE
1213nucomp_eqeq_p(VALUE self, VALUE other)
1214{
1215 if (RB_TYPE_P(other, T_COMPLEX)) {
1216 get_dat2(self, other);
1217
1218 return RBOOL(f_eqeq_p(adat->real, bdat->real) &&
1219 f_eqeq_p(adat->imag, bdat->imag));
1220 }
1221 if (k_numeric_p(other) && f_real_p(other)) {
1222 get_dat1(self);
1223
1224 return RBOOL(f_eqeq_p(dat->real, other) && f_zero_p(dat->imag));
1225 }
1226 return RBOOL(f_eqeq_p(other, self));
1227}
1228
1229static bool
1230nucomp_real_p(VALUE self)
1231{
1232 get_dat1(self);
1233 return f_zero_p(dat->imag);
1234}
1235
1236/*
1237 * call-seq:
1238 * self <=> other -> -1, 0, 1, or nil
1239 *
1240 * Compares +self+ and +other+.
1241 *
1242 * Returns:
1243 *
1244 * - <tt>self.real <=> other.real</tt> if both of the following are true:
1245 *
1246 * - <tt>self.imag == 0</tt>.
1247 * - <tt>other.imag == 0</tt> (always true if +other+ is numeric but not complex).
1248 *
1249 * - +nil+ otherwise.
1250 *
1251 * Examples:
1252 *
1253 * Complex.rect(2) <=> 3 # => -1
1254 * Complex.rect(2) <=> 2 # => 0
1255 * Complex.rect(2) <=> 1 # => 1
1256 * Complex.rect(2, 1) <=> 1 # => nil # self.imag not zero.
1257 * Complex.rect(1) <=> Complex.rect(1, 1) # => nil # object.imag not zero.
1258 * Complex.rect(1) <=> 'Foo' # => nil # object.imag not defined.
1259 *
1260 * \Class \Complex includes module Comparable,
1261 * each of whose methods uses Complex#<=> for comparison.
1262 */
1263static VALUE
1264nucomp_cmp(VALUE self, VALUE other)
1265{
1266 if (!k_numeric_p(other)) {
1267 return rb_num_coerce_cmp(self, other, idCmp);
1268 }
1269 if (!nucomp_real_p(self)) {
1270 return Qnil;
1271 }
1272 if (RB_TYPE_P(other, T_COMPLEX)) {
1273 if (nucomp_real_p(other)) {
1274 get_dat2(self, other);
1275 return rb_funcall(adat->real, idCmp, 1, bdat->real);
1276 }
1277 }
1278 else {
1279 get_dat1(self);
1280 if (f_real_p(other)) {
1281 return rb_funcall(dat->real, idCmp, 1, other);
1282 }
1283 else {
1284 return rb_num_coerce_cmp(dat->real, other, idCmp);
1285 }
1286 }
1287 return Qnil;
1288}
1289
1290/* :nodoc: */
1291static VALUE
1292nucomp_coerce(VALUE self, VALUE other)
1293{
1294 if (RB_TYPE_P(other, T_COMPLEX))
1295 return rb_assoc_new(other, self);
1296 if (k_numeric_p(other) && f_real_p(other))
1297 return rb_assoc_new(f_complex_new_bang1(CLASS_OF(self), other), self);
1298
1299 rb_raise(rb_eTypeError, "%"PRIsVALUE" can't be coerced into %"PRIsVALUE,
1300 rb_obj_class(other), rb_obj_class(self));
1301 return Qnil;
1302}
1303
1304/*
1305 * call-seq:
1306 * abs -> float
1307 *
1308 * Returns the absolute value (magnitude) for +self+;
1309 * see {polar coordinates}[rdoc-ref:Complex@Polar+Coordinates]:
1310 *
1311 * Complex.polar(-1, 0).abs # => 1.0
1312 *
1313 * If +self+ was created with
1314 * {rectangular coordinates}[rdoc-ref:Complex@Rectangular+Coordinates], the returned value
1315 * is computed, and may be inexact:
1316 *
1317 * Complex.rectangular(1, 1).abs # => 1.4142135623730951 # The square root of 2.
1318 *
1319 */
1320VALUE
1321rb_complex_abs(VALUE self)
1322{
1323 get_dat1(self);
1324
1325 if (f_zero_p(dat->real)) {
1326 VALUE a = f_abs(dat->imag);
1327 if (RB_FLOAT_TYPE_P(dat->real) && !RB_FLOAT_TYPE_P(dat->imag))
1328 a = f_to_f(a);
1329 return a;
1330 }
1331 if (f_zero_p(dat->imag)) {
1332 VALUE a = f_abs(dat->real);
1333 if (!RB_FLOAT_TYPE_P(dat->real) && RB_FLOAT_TYPE_P(dat->imag))
1334 a = f_to_f(a);
1335 return a;
1336 }
1337 return rb_math_hypot(dat->real, dat->imag);
1338}
1339
1340/*
1341 * call-seq:
1342 * abs2 -> float
1343 *
1344 * Returns square of the absolute value (magnitude) for +self+;
1345 * see {polar coordinates}[rdoc-ref:Complex@Polar+Coordinates]:
1346 *
1347 * Complex.polar(2, 2).abs2 # => 4.0
1348 *
1349 * If +self+ was created with
1350 * {rectangular coordinates}[rdoc-ref:Complex@Rectangular+Coordinates], the returned value
1351 * is computed, and may be inexact:
1352 *
1353 * Complex.rectangular(1.0/3, 1.0/3).abs2 # => 0.2222222222222222
1354 *
1355 */
1356static VALUE
1357nucomp_abs2(VALUE self)
1358{
1359 get_dat1(self);
1360 return f_add(f_mul(dat->real, dat->real),
1361 f_mul(dat->imag, dat->imag));
1362}
1363
1364/*
1365 * call-seq:
1366 * arg -> float
1367 *
1368 * Returns the argument (angle) for +self+ in radians;
1369 * see {polar coordinates}[rdoc-ref:Complex@Polar+Coordinates]:
1370 *
1371 * Complex.polar(3, Math::PI/2).arg # => 1.57079632679489660
1372 *
1373 * If +self+ was created with
1374 * {rectangular coordinates}[rdoc-ref:Complex@Rectangular+Coordinates], the returned value
1375 * is computed, and may be inexact:
1376 *
1377 * Complex.polar(1, 1.0/3).arg # => 0.33333333333333326
1378 *
1379 */
1380VALUE
1381rb_complex_arg(VALUE self)
1382{
1383 get_dat1(self);
1384 return rb_math_atan2(dat->imag, dat->real);
1385}
1386
1387/*
1388 * call-seq:
1389 * rect -> array
1390 *
1391 * Returns the array <tt>[self.real, self.imag]</tt>:
1392 *
1393 * Complex.rect(1, 2).rect # => [1, 2]
1394 *
1395 * See {Rectangular Coordinates}[rdoc-ref:Complex@Rectangular+Coordinates].
1396 *
1397 * If +self+ was created with
1398 * {polar coordinates}[rdoc-ref:Complex@Polar+Coordinates], the returned value
1399 * is computed, and may be inexact:
1400 *
1401 * Complex.polar(1.0, 1.0).rect # => [0.5403023058681398, 0.8414709848078965]
1402 *
1403 *
1404 * Complex#rectangular is an alias for Complex#rect.
1405 */
1406static VALUE
1407nucomp_rect(VALUE self)
1408{
1409 get_dat1(self);
1410 return rb_assoc_new(dat->real, dat->imag);
1411}
1412
1413/*
1414 * call-seq:
1415 * polar -> array
1416 *
1417 * Returns the array <tt>[self.abs, self.arg]</tt>:
1418 *
1419 * Complex.polar(1, 2).polar # => [1.0, 2.0]
1420 *
1421 * See {Polar Coordinates}[rdoc-ref:Complex@Polar+Coordinates].
1422 *
1423 * If +self+ was created with
1424 * {rectangular coordinates}[rdoc-ref:Complex@Rectangular+Coordinates], the returned value
1425 * is computed, and may be inexact:
1426 *
1427 * Complex.rect(1, 1).polar # => [1.4142135623730951, 0.7853981633974483]
1428 *
1429 */
1430static VALUE
1431nucomp_polar(VALUE self)
1432{
1433 return rb_assoc_new(f_abs(self), f_arg(self));
1434}
1435
1436/*
1437 * call-seq:
1438 * conj -> complex
1439 *
1440 * Returns the conjugate of +self+, <tt>Complex.rect(self.imag, self.real)</tt>:
1441 *
1442 * Complex.rect(1, 2).conj # => (1-2i)
1443 *
1444 */
1445VALUE
1446rb_complex_conjugate(VALUE self)
1447{
1448 get_dat1(self);
1449 return f_complex_new2(CLASS_OF(self), dat->real, f_negate(dat->imag));
1450}
1451
1452/*
1453 * call-seq:
1454 * real? -> false
1455 *
1456 * Returns +false+; for compatibility with Numeric#real?.
1457 */
1458static VALUE
1459nucomp_real_p_m(VALUE self)
1460{
1461 return Qfalse;
1462}
1463
1464/*
1465 * call-seq:
1466 * denominator -> integer
1467 *
1468 * Returns the denominator of +self+, which is
1469 * the {least common multiple}[https://en.wikipedia.org/wiki/Least_common_multiple]
1470 * of <tt>self.real.denominator</tt> and <tt>self.imag.denominator</tt>:
1471 *
1472 * Complex.rect(Rational(1, 2), Rational(2, 3)).denominator # => 6
1473 *
1474 * Note that <tt>n.denominator</tt> of a non-rational numeric is +1+.
1475 *
1476 * Related: Complex#numerator.
1477 */
1478static VALUE
1479nucomp_denominator(VALUE self)
1480{
1481 get_dat1(self);
1482 return rb_lcm(f_denominator(dat->real), f_denominator(dat->imag));
1483}
1484
1485/*
1486 * call-seq:
1487 * numerator -> new_complex
1488 *
1489 * Returns the \Complex object created from the numerators
1490 * of the real and imaginary parts of +self+,
1491 * after converting each part to the
1492 * {lowest common denominator}[https://en.wikipedia.org/wiki/Lowest_common_denominator]
1493 * of the two:
1494 *
1495 * c = Complex.rect(Rational(2, 3), Rational(3, 4)) # => ((2/3)+(3/4)*i)
1496 * c.numerator # => (8+9i)
1497 *
1498 * In this example, the lowest common denominator of the two parts is 12;
1499 * the two converted parts may be thought of as \Rational(8, 12) and \Rational(9, 12),
1500 * whose numerators, respectively, are 8 and 9;
1501 * so the returned value of <tt>c.numerator</tt> is <tt>Complex.rect(8, 9)</tt>.
1502 *
1503 * Related: Complex#denominator.
1504 */
1505static VALUE
1506nucomp_numerator(VALUE self)
1507{
1508 VALUE cd;
1509
1510 get_dat1(self);
1511
1512 cd = nucomp_denominator(self);
1513 return f_complex_new2(CLASS_OF(self),
1514 f_mul(f_numerator(dat->real),
1515 f_div(cd, f_denominator(dat->real))),
1516 f_mul(f_numerator(dat->imag),
1517 f_div(cd, f_denominator(dat->imag))));
1518}
1519
1520/* :nodoc: */
1521st_index_t
1522rb_complex_hash(VALUE self)
1523{
1524 st_index_t v, h[2];
1525 VALUE n;
1526
1527 get_dat1(self);
1528 n = rb_hash(dat->real);
1529 h[0] = NUM2LONG(n);
1530 n = rb_hash(dat->imag);
1531 h[1] = NUM2LONG(n);
1532 v = rb_memhash(h, sizeof(h));
1533 return v;
1534}
1535
1536/*
1537 * :call-seq:
1538 * hash -> integer
1539 *
1540 * Returns the integer hash value for +self+.
1541 *
1542 * Two \Complex objects created from the same values will have the same hash value
1543 * (and will compare using #eql?):
1544 *
1545 * Complex.rect(1, 2).hash == Complex.rect(1, 2).hash # => true
1546 *
1547 */
1548static VALUE
1549nucomp_hash(VALUE self)
1550{
1551 return ST2FIX(rb_complex_hash(self));
1552}
1553
1554/* :nodoc: */
1555static VALUE
1556nucomp_eql_p(VALUE self, VALUE other)
1557{
1558 if (RB_TYPE_P(other, T_COMPLEX)) {
1559 get_dat2(self, other);
1560
1561 return RBOOL((CLASS_OF(adat->real) == CLASS_OF(bdat->real)) &&
1562 (CLASS_OF(adat->imag) == CLASS_OF(bdat->imag)) &&
1563 f_eqeq_p(self, other));
1564
1565 }
1566 return Qfalse;
1567}
1568
1569inline static int
1570f_signbit(VALUE x)
1571{
1572 if (RB_FLOAT_TYPE_P(x)) {
1573 double f = RFLOAT_VALUE(x);
1574 return !isnan(f) && signbit(f);
1575 }
1576 return f_negative_p(x);
1577}
1578
1579inline static int
1580f_tpositive_p(VALUE x)
1581{
1582 return !f_signbit(x);
1583}
1584
1585static VALUE
1586f_format(VALUE self, VALUE s, VALUE (*func)(VALUE))
1587{
1588 int impos;
1589
1590 get_dat1(self);
1591
1592 impos = f_tpositive_p(dat->imag);
1593
1594 rb_str_concat(s, (*func)(dat->real));
1595 rb_str_cat2(s, !impos ? "-" : "+");
1596
1597 rb_str_concat(s, (*func)(f_abs(dat->imag)));
1598 if (!rb_isdigit(RSTRING_PTR(s)[RSTRING_LEN(s) - 1]))
1599 rb_str_cat2(s, "*");
1600 rb_str_cat2(s, "i");
1601
1602 return s;
1603}
1604
1605/*
1606 * call-seq:
1607 * to_s -> string
1608 *
1609 * Returns a string representation of +self+:
1610 *
1611 * Complex.rect(2).to_s # => "2+0i"
1612 * Complex.rect(-8, 6).to_s # => "-8+6i"
1613 * Complex.rect(0, Rational(1, 2)).to_s # => "0+1/2i"
1614 * Complex.rect(0, Float::INFINITY).to_s # => "0+Infinity*i"
1615 * Complex.rect(Float::NAN, Float::NAN).to_s # => "NaN+NaN*i"
1616 *
1617 */
1618static VALUE
1619nucomp_to_s(VALUE self)
1620{
1621 return f_format(self, rb_usascii_str_new2(""), rb_String);
1622}
1623
1624/*
1625 * call-seq:
1626 * inspect -> string
1627 *
1628 * Returns a string representation of +self+:
1629 *
1630 * Complex.rect(2).inspect # => "(2+0i)"
1631 * Complex.rect(-8, 6).inspect # => "(-8+6i)"
1632 * Complex.rect(0, Rational(1, 2)).inspect # => "(0+(1/2)*i)"
1633 * Complex.rect(0, Float::INFINITY).inspect # => "(0+Infinity*i)"
1634 * Complex.rect(Float::NAN, Float::NAN).inspect # => "(NaN+NaN*i)"
1635 *
1636 */
1637static VALUE
1638nucomp_inspect(VALUE self)
1639{
1640 VALUE s;
1641
1642 s = rb_usascii_str_new2("(");
1643 f_format(self, s, rb_inspect);
1644 rb_str_cat2(s, ")");
1645
1646 return s;
1647}
1648
1649#define FINITE_TYPE_P(v) (RB_INTEGER_TYPE_P(v) || RB_TYPE_P(v, T_RATIONAL))
1650
1651/*
1652 * call-seq:
1653 * finite? -> true or false
1654 *
1655 * Returns +true+ if both <tt>self.real.finite?</tt> and <tt>self.imag.finite?</tt>
1656 * are true, +false+ otherwise:
1657 *
1658 * Complex.rect(1, 1).finite? # => true
1659 * Complex.rect(Float::INFINITY, 0).finite? # => false
1660 *
1661 * Related: Numeric#finite?, Float#finite?.
1662 */
1663static VALUE
1664rb_complex_finite_p(VALUE self)
1665{
1666 get_dat1(self);
1667
1668 return RBOOL(f_finite_p(dat->real) && f_finite_p(dat->imag));
1669}
1670
1671/*
1672 * call-seq:
1673 * infinite? -> 1 or nil
1674 *
1675 * Returns +1+ if either <tt>self.real.infinite?</tt> or <tt>self.imag.infinite?</tt>
1676 * is true, +nil+ otherwise:
1677 *
1678 * Complex.rect(Float::INFINITY, 0).infinite? # => 1
1679 * Complex.rect(1, 1).infinite? # => nil
1680 *
1681 * Related: Numeric#infinite?, Float#infinite?.
1682 */
1683static VALUE
1684rb_complex_infinite_p(VALUE self)
1685{
1686 get_dat1(self);
1687
1688 if (!f_infinite_p(dat->real) && !f_infinite_p(dat->imag)) {
1689 return Qnil;
1690 }
1691 return ONE;
1692}
1693
1694/* :nodoc: */
1695static VALUE
1696nucomp_dumper(VALUE self)
1697{
1698 return self;
1699}
1700
1701/* :nodoc: */
1702static VALUE
1703nucomp_loader(VALUE self, VALUE a)
1704{
1705 get_dat1(self);
1706
1707 RCOMPLEX_SET_REAL(dat, rb_ivar_get(a, id_i_real));
1708 RCOMPLEX_SET_IMAG(dat, rb_ivar_get(a, id_i_imag));
1709 OBJ_FREEZE(self);
1710
1711 return self;
1712}
1713
1714/* :nodoc: */
1715static VALUE
1716nucomp_marshal_dump(VALUE self)
1717{
1718 VALUE a;
1719 get_dat1(self);
1720
1721 a = rb_assoc_new(dat->real, dat->imag);
1722 rb_copy_generic_ivar(a, self);
1723 return a;
1724}
1725
1726/* :nodoc: */
1727static VALUE
1728nucomp_marshal_load(VALUE self, VALUE a)
1729{
1730 Check_Type(a, T_ARRAY);
1731 if (RARRAY_LEN(a) != 2)
1732 rb_raise(rb_eArgError, "marshaled complex must have an array whose length is 2 but %ld", RARRAY_LEN(a));
1733 rb_ivar_set(self, id_i_real, RARRAY_AREF(a, 0));
1734 rb_ivar_set(self, id_i_imag, RARRAY_AREF(a, 1));
1735 return self;
1736}
1737
1738VALUE
1739rb_complex_raw(VALUE x, VALUE y)
1740{
1741 return nucomp_s_new_internal(rb_cComplex, x, y);
1742}
1743
1744VALUE
1745rb_complex_new(VALUE x, VALUE y)
1746{
1747 return nucomp_s_canonicalize_internal(rb_cComplex, x, y);
1748}
1749
1750VALUE
1751rb_complex_new_polar(VALUE x, VALUE y)
1752{
1753 return f_complex_polar(rb_cComplex, x, y);
1754}
1755
1756VALUE
1757rb_Complex(VALUE x, VALUE y)
1758{
1759 VALUE a[2];
1760 a[0] = x;
1761 a[1] = y;
1762 return nucomp_s_convert(2, a, rb_cComplex);
1763}
1764
1765VALUE
1766rb_dbl_complex_new(double real, double imag)
1767{
1768 return rb_complex_raw(DBL2NUM(real), DBL2NUM(imag));
1769}
1770
1771/*
1772 * call-seq:
1773 * to_i -> integer
1774 *
1775 * Returns the value of <tt>self.real</tt> as an Integer, if possible:
1776 *
1777 * Complex.rect(1, 0).to_i # => 1
1778 * Complex.rect(1, Rational(0, 1)).to_i # => 1
1779 *
1780 * Raises RangeError if <tt>self.imag</tt> is not exactly zero
1781 * (either <tt>Integer(0)</tt> or <tt>Rational(0, n)</tt>).
1782 */
1783static VALUE
1784nucomp_to_i(VALUE self)
1785{
1786 get_dat1(self);
1787
1788 if (!k_exact_zero_p(dat->imag)) {
1789 rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Integer",
1790 self);
1791 }
1792 return f_to_i(dat->real);
1793}
1794
1795/*
1796 * call-seq:
1797 * to_f -> float
1798 *
1799 * Returns the value of <tt>self.real</tt> as a Float, if possible:
1800 *
1801 * Complex.rect(1, 0).to_f # => 1.0
1802 * Complex.rect(1, Rational(0, 1)).to_f # => 1.0
1803 *
1804 * Raises RangeError if <tt>self.imag</tt> is not exactly zero
1805 * (either <tt>Integer(0)</tt> or <tt>Rational(0, n)</tt>).
1806 */
1807static VALUE
1808nucomp_to_f(VALUE self)
1809{
1810 get_dat1(self);
1811
1812 if (!k_exact_zero_p(dat->imag)) {
1813 rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Float",
1814 self);
1815 }
1816 return f_to_f(dat->real);
1817}
1818
1819/*
1820 * call-seq:
1821 * to_r -> rational
1822 *
1823 * Returns the value of <tt>self.real</tt> as a Rational, if possible:
1824 *
1825 * Complex.rect(1, 0).to_r # => (1/1)
1826 * Complex.rect(1, Rational(0, 1)).to_r # => (1/1)
1827 * Complex.rect(1, 0.0).to_r # => (1/1)
1828 *
1829 * Raises RangeError if <tt>self.imag</tt> is not exactly zero
1830 * (either <tt>Integer(0)</tt> or <tt>Rational(0, n)</tt>)
1831 * and <tt>self.imag.to_r</tt> is not exactly zero.
1832 *
1833 * Related: Complex#rationalize.
1834 */
1835static VALUE
1836nucomp_to_r(VALUE self)
1837{
1838 get_dat1(self);
1839
1840 if (RB_FLOAT_TYPE_P(dat->imag) && FLOAT_ZERO_P(dat->imag)) {
1841 /* Do nothing here */
1842 }
1843 else if (!k_exact_zero_p(dat->imag)) {
1844 VALUE imag = rb_check_convert_type_with_id(dat->imag, T_RATIONAL, "Rational", idTo_r);
1845 if (NIL_P(imag) || !k_exact_zero_p(imag)) {
1846 rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Rational",
1847 self);
1848 }
1849 }
1850 return rb_funcallv(dat->real, id_to_r, 0, 0);
1851}
1852
1853/*
1854 * call-seq:
1855 * rationalize(epsilon = nil) -> rational
1856 *
1857 * Returns a Rational object whose value is exactly or approximately
1858 * equivalent to that of <tt>self.real</tt>.
1859 *
1860 * With no argument +epsilon+ given, returns a \Rational object
1861 * whose value is exactly equal to that of <tt>self.real.rationalize</tt>:
1862 *
1863 * Complex.rect(1, 0).rationalize # => (1/1)
1864 * Complex.rect(1, Rational(0, 1)).rationalize # => (1/1)
1865 * Complex.rect(3.14159, 0).rationalize # => (314159/100000)
1866 *
1867 * With argument +epsilon+ given, returns a \Rational object
1868 * whose value is exactly or approximately equal to that of <tt>self.real</tt>
1869 * to the given precision:
1870 *
1871 * Complex.rect(3.14159, 0).rationalize(0.1) # => (16/5)
1872 * Complex.rect(3.14159, 0).rationalize(0.01) # => (22/7)
1873 * Complex.rect(3.14159, 0).rationalize(0.001) # => (201/64)
1874 * Complex.rect(3.14159, 0).rationalize(0.0001) # => (333/106)
1875 * Complex.rect(3.14159, 0).rationalize(0.00001) # => (355/113)
1876 * Complex.rect(3.14159, 0).rationalize(0.000001) # => (7433/2366)
1877 * Complex.rect(3.14159, 0).rationalize(0.0000001) # => (9208/2931)
1878 * Complex.rect(3.14159, 0).rationalize(0.00000001) # => (47460/15107)
1879 * Complex.rect(3.14159, 0).rationalize(0.000000001) # => (76149/24239)
1880 * Complex.rect(3.14159, 0).rationalize(0.0000000001) # => (314159/100000)
1881 * Complex.rect(3.14159, 0).rationalize(0.0) # => (3537115888337719/1125899906842624)
1882 *
1883 * Related: Complex#to_r.
1884 */
1885static VALUE
1886nucomp_rationalize(int argc, VALUE *argv, VALUE self)
1887{
1888 get_dat1(self);
1889
1890 rb_check_arity(argc, 0, 1);
1891
1892 if (!k_exact_zero_p(dat->imag)) {
1893 rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Rational",
1894 self);
1895 }
1896 return rb_funcallv(dat->real, id_rationalize, argc, argv);
1897}
1898
1899/*
1900 * call-seq:
1901 * to_c -> self
1902 *
1903 * Returns +self+.
1904 */
1905static VALUE
1906nucomp_to_c(VALUE self)
1907{
1908 return self;
1909}
1910
1911/*
1912 * call-seq:
1913 * to_c -> complex
1914 *
1915 * Returns +self+ as a Complex object.
1916 */
1917static VALUE
1918numeric_to_c(VALUE self)
1919{
1920 return rb_complex_new1(self);
1921}
1922
1923inline static int
1924issign(int c)
1925{
1926 return (c == '-' || c == '+');
1927}
1928
1929static int
1930read_sign(const char **s,
1931 char **b)
1932{
1933 int sign = '?';
1934
1935 if (issign(**s)) {
1936 sign = **b = **s;
1937 (*s)++;
1938 (*b)++;
1939 }
1940 return sign;
1941}
1942
1943inline static int
1944isdecimal(int c)
1945{
1946 return isdigit((unsigned char)c);
1947}
1948
1949static int
1950read_digits(const char **s, int strict,
1951 char **b)
1952{
1953 int us = 1;
1954
1955 if (!isdecimal(**s))
1956 return 0;
1957
1958 while (isdecimal(**s) || **s == '_') {
1959 if (**s == '_') {
1960 if (us) {
1961 if (strict) return 0;
1962 break;
1963 }
1964 us = 1;
1965 }
1966 else {
1967 **b = **s;
1968 (*b)++;
1969 us = 0;
1970 }
1971 (*s)++;
1972 }
1973 if (us)
1974 do {
1975 (*s)--;
1976 } while (**s == '_');
1977 return 1;
1978}
1979
1980inline static int
1981islettere(int c)
1982{
1983 return (c == 'e' || c == 'E');
1984}
1985
1986static int
1987read_num(const char **s, int strict,
1988 char **b)
1989{
1990 if (**s != '.') {
1991 if (!read_digits(s, strict, b))
1992 return 0;
1993 }
1994
1995 if (**s == '.') {
1996 **b = **s;
1997 (*s)++;
1998 (*b)++;
1999 if (!read_digits(s, strict, b)) {
2000 (*b)--;
2001 return 0;
2002 }
2003 }
2004
2005 if (islettere(**s)) {
2006 **b = **s;
2007 (*s)++;
2008 (*b)++;
2009 read_sign(s, b);
2010 if (!read_digits(s, strict, b)) {
2011 (*b)--;
2012 return 0;
2013 }
2014 }
2015 return 1;
2016}
2017
2018inline static int
2019read_den(const char **s, int strict,
2020 char **b)
2021{
2022 if (!read_digits(s, strict, b))
2023 return 0;
2024 return 1;
2025}
2026
2027static int
2028read_rat_nos(const char **s, int strict,
2029 char **b)
2030{
2031 if (!read_num(s, strict, b))
2032 return 0;
2033 if (**s == '/') {
2034 **b = **s;
2035 (*s)++;
2036 (*b)++;
2037 if (!read_den(s, strict, b)) {
2038 (*b)--;
2039 return 0;
2040 }
2041 }
2042 return 1;
2043}
2044
2045static int
2046read_rat(const char **s, int strict,
2047 char **b)
2048{
2049 read_sign(s, b);
2050 if (!read_rat_nos(s, strict, b))
2051 return 0;
2052 return 1;
2053}
2054
2055inline static int
2056isimagunit(int c)
2057{
2058 return (c == 'i' || c == 'I' ||
2059 c == 'j' || c == 'J');
2060}
2061
2062static VALUE
2063str2num(char *s)
2064{
2065 if (strchr(s, '/'))
2066 return rb_cstr_to_rat(s, 0);
2067 if (strpbrk(s, ".eE"))
2068 return DBL2NUM(rb_cstr_to_dbl(s, 0));
2069 return rb_cstr_to_inum(s, 10, 0);
2070}
2071
2072static int
2073read_comp(const char **s, int strict,
2074 VALUE *ret, char **b)
2075{
2076 char *bb;
2077 int sign;
2078 VALUE num, num2;
2079
2080 bb = *b;
2081
2082 sign = read_sign(s, b);
2083
2084 if (isimagunit(**s)) {
2085 (*s)++;
2086 num = INT2FIX((sign == '-') ? -1 : + 1);
2087 *ret = rb_complex_new2(ZERO, num);
2088 return 1; /* e.g. "i" */
2089 }
2090
2091 if (!read_rat_nos(s, strict, b)) {
2092 **b = '\0';
2093 num = str2num(bb);
2094 *ret = rb_complex_new2(num, ZERO);
2095 return 0; /* e.g. "-" */
2096 }
2097 **b = '\0';
2098 num = str2num(bb);
2099
2100 if (isimagunit(**s)) {
2101 (*s)++;
2102 *ret = rb_complex_new2(ZERO, num);
2103 return 1; /* e.g. "3i" */
2104 }
2105
2106 if (**s == '@') {
2107 int st;
2108
2109 (*s)++;
2110 bb = *b;
2111 st = read_rat(s, strict, b);
2112 **b = '\0';
2113 if (strlen(bb) < 1 ||
2114 !isdecimal(*(bb + strlen(bb) - 1))) {
2115 *ret = rb_complex_new2(num, ZERO);
2116 return 0; /* e.g. "1@-" */
2117 }
2118 num2 = str2num(bb);
2119 *ret = rb_complex_new_polar(num, num2);
2120 if (!st)
2121 return 0; /* e.g. "1@2." */
2122 else
2123 return 1; /* e.g. "1@2" */
2124 }
2125
2126 if (issign(**s)) {
2127 bb = *b;
2128 sign = read_sign(s, b);
2129 if (isimagunit(**s))
2130 num2 = INT2FIX((sign == '-') ? -1 : + 1);
2131 else {
2132 if (!read_rat_nos(s, strict, b)) {
2133 *ret = rb_complex_new2(num, ZERO);
2134 return 0; /* e.g. "1+xi" */
2135 }
2136 **b = '\0';
2137 num2 = str2num(bb);
2138 }
2139 if (!isimagunit(**s)) {
2140 *ret = rb_complex_new2(num, ZERO);
2141 return 0; /* e.g. "1+3x" */
2142 }
2143 (*s)++;
2144 *ret = rb_complex_new2(num, num2);
2145 return 1; /* e.g. "1+2i" */
2146 }
2147 /* !(@, - or +) */
2148 {
2149 *ret = rb_complex_new2(num, ZERO);
2150 return 1; /* e.g. "3" */
2151 }
2152}
2153
2154inline static void
2155skip_ws(const char **s)
2156{
2157 while (isspace((unsigned char)**s))
2158 (*s)++;
2159}
2160
2161static int
2162parse_comp(const char *s, int strict, VALUE *num)
2163{
2164 char *buf, *b;
2165 VALUE tmp;
2166 int ret = 1;
2167
2168 buf = ALLOCV_N(char, tmp, strlen(s) + 1);
2169 b = buf;
2170
2171 skip_ws(&s);
2172 if (!read_comp(&s, strict, num, &b)) {
2173 ret = 0;
2174 }
2175 else {
2176 skip_ws(&s);
2177
2178 if (strict)
2179 if (*s != '\0')
2180 ret = 0;
2181 }
2182 ALLOCV_END(tmp);
2183
2184 return ret;
2185}
2186
2187static VALUE
2188string_to_c_strict(VALUE self, int raise)
2189{
2190 char *s;
2191 VALUE num;
2192
2193 rb_must_asciicompat(self);
2194
2195 if (raise) {
2196 s = StringValueCStr(self);
2197 }
2198 else if (!(s = rb_str_to_cstr(self))) {
2199 return Qnil;
2200 }
2201
2202 if (!parse_comp(s, TRUE, &num)) {
2203 if (!raise) return Qnil;
2204 rb_raise(rb_eArgError, "invalid value for convert(): %+"PRIsVALUE,
2205 self);
2206 }
2207
2208 return num;
2209}
2210
2211/*
2212 * call-seq:
2213 * to_c -> complex
2214 *
2215 * Returns a Complex object:
2216 * parses the leading substring of +self+
2217 * to extract two numeric values that become the coordinates of the complex object.
2218 *
2219 * The substring is interpreted as containing
2220 * either rectangular coordinates (real and imaginary parts)
2221 * or polar coordinates (magnitude and angle parts),
2222 * depending on an included or implied "separator" character:
2223 *
2224 * - <tt>'+'</tt>, <tt>'-'</tt>, or no separator: rectangular coordinates.
2225 * - <tt>'@'</tt>: polar coordinates.
2226 *
2227 * <b>In Brief</b>
2228 *
2229 * In these examples, we use method Complex#rect to display rectangular coordinates,
2230 * and method Complex#polar to display polar coordinates.
2231 *
2232 * # Rectangular coordinates.
2233 *
2234 * # Real-only: no separator; imaginary part is zero.
2235 * '9'.to_c.rect # => [9, 0] # Integer.
2236 * '-9'.to_c.rect # => [-9, 0] # Integer (negative).
2237 * '2.5'.to_c.rect # => [2.5, 0] # Float.
2238 * '1.23e-14'.to_c.rect # => [1.23e-14, 0] # Float with exponent.
2239 * '2.5/1'.to_c.rect # => [(5/2), 0] # Rational.
2240 *
2241 * # Some things are ignored.
2242 * 'foo1'.to_c.rect # => [0, 0] # Unparsed entire substring.
2243 * '1foo'.to_c.rect # => [1, 0] # Unparsed trailing substring.
2244 * ' 1 '.to_c.rect # => [1, 0] # Leading and trailing whitespace.
2245 * *
2246 * # Imaginary only: trailing 'i' required; real part is zero.
2247 * '9i'.to_c.rect # => [0, 9]
2248 * '-9i'.to_c.rect # => [0, -9]
2249 * '2.5i'.to_c.rect # => [0, 2.5]
2250 * '1.23e-14i'.to_c.rect # => [0, 1.23e-14]
2251 * '2.5/1i'.to_c.rect # => [0, (5/2)]
2252 *
2253 * # Real and imaginary; '+' or '-' separator; trailing 'i' required.
2254 * '2+3i'.to_c.rect # => [2, 3]
2255 * '-2-3i'.to_c.rect # => [-2, -3]
2256 * '2.5+3i'.to_c.rect # => [2.5, 3]
2257 * '2.5+3/2i'.to_c.rect # => [2.5, (3/2)]
2258 *
2259 * # Polar coordinates; '@' separator; magnitude required.
2260 * '1.0@0'.to_c.polar # => [1.0, 0.0]
2261 * '1.0@'.to_c.polar # => [1.0, 0.0]
2262 * "1.0@#{Math::PI}".to_c.polar # => [1.0, 3.141592653589793]
2263 * "1.0@#{Math::PI/2}".to_c.polar # => [1.0, 1.5707963267948966]
2264 *
2265 * <b>Parsed Values</b>
2266 *
2267 * The parsing may be thought of as searching for numeric literals
2268 * embedded in the substring.
2269 *
2270 * This section shows how the method parses numeric values from leading substrings.
2271 * The examples show real-only or imaginary-only parsing;
2272 * the parsing is the same for each part.
2273 *
2274 * '1foo'.to_c # => (1+0i) # Ignores trailing unparsed characters.
2275 * ' 1 '.to_c # => (1+0i) # Ignores leading and trailing whitespace.
2276 * 'x1'.to_c # => (0+0i) # Finds no leading numeric.
2277 *
2278 * # Integer literal embedded in the substring.
2279 * '1'.to_c # => (1+0i)
2280 * '-1'.to_c # => (-1+0i)
2281 * '1i'.to_c # => (0+1i)
2282 *
2283 * # Integer literals that don't work.
2284 * '0b100'.to_c # => (0+0i) # Not parsed as binary.
2285 * '0o100'.to_c # => (0+0i) # Not parsed as octal.
2286 * '0d100'.to_c # => (0+0i) # Not parsed as decimal.
2287 * '0x100'.to_c # => (0+0i) # Not parsed as hexadecimal.
2288 * '010'.to_c # => (10+0i) # Not parsed as octal.
2289 *
2290 * # Float literals:
2291 * '3.14'.to_c # => (3.14+0i)
2292 * '3.14i'.to_c # => (0+3.14i)
2293 * '1.23e4'.to_c # => (12300.0+0i)
2294 * '1.23e+4'.to_c # => (12300.0+0i)
2295 * '1.23e-4'.to_c # => (0.000123+0i)
2296 *
2297 * # Rational literals:
2298 * '1/2'.to_c # => ((1/2)+0i)
2299 * '-1/2'.to_c # => ((-1/2)+0i)
2300 * '1/2r'.to_c # => ((1/2)+0i)
2301 * '-1/2r'.to_c # => ((-1/2)+0i)
2302 *
2303 * <b>Rectangular Coordinates</b>
2304 *
2305 * With separator <tt>'+'</tt> or <tt>'-'</tt>,
2306 * or with no separator,
2307 * interprets the values as rectangular coordinates: real and imaginary.
2308 *
2309 * With no separator, assigns a single value to either the real or the imaginary part:
2310 *
2311 * ''.to_c # => (0+0i) # Defaults to zero.
2312 * '1'.to_c # => (1+0i) # Real (no trailing 'i').
2313 * '1i'.to_c # => (0+1i) # Imaginary (trailing 'i').
2314 * 'i'.to_c # => (0+1i) # Special case (imaginary 1).
2315 *
2316 * With separator <tt>'+'</tt>, both parts positive (or zero):
2317 *
2318 * # Without trailing 'i'.
2319 * '+'.to_c # => (0+0i) # No values: defaults to zero.
2320 * '+1'.to_c # => (1+0i) # Value after '+': real only.
2321 * '1+'.to_c # => (1+0i) # Value before '+': real only.
2322 * '2+1'.to_c # => (2+0i) # Values before and after '+': real and imaginary.
2323 * # With trailing 'i'.
2324 * '+1i'.to_c # => (0+1i) # Value after '+': imaginary only.
2325 * '2+i'.to_c # => (2+1i) # Value before '+': real and imaginary 1.
2326 * '2+1i'.to_c # => (2+1i) # Values before and after '+': real and imaginary.
2327 *
2328 * With separator <tt>'-'</tt>, negative imaginary part:
2329 *
2330 * # Without trailing 'i'.
2331 * '-'.to_c # => (0+0i) # No values: defaults to zero.
2332 * '-1'.to_c # => (-1+0i) # Value after '-': negative real, zero imaginary.
2333 * '1-'.to_c # => (1+0i) # Value before '-': positive real, zero imaginary.
2334 * '2-1'.to_c # => (2+0i) # Values before and after '-': positive real, zero imaginary.
2335 * # With trailing 'i'.
2336 * '-1i'.to_c # => (0-1i) # Value after '-': negative real, zero imaginary.
2337 * '2-i'.to_c # => (2-1i) # Value before '-': positive real, negative imaginary.
2338 * '2-1i'.to_c # => (2-1i) # Values before and after '-': positive real, negative imaginary.
2339 *
2340 * Note that the suffixed character <tt>'i'</tt>
2341 * may instead be one of <tt>'I'</tt>, <tt>'j'</tt>, or <tt>'J'</tt>,
2342 * with the same effect.
2343 *
2344 * <b>Polar Coordinates</b>
2345 *
2346 * With separator <tt>'@'</tt>)
2347 * interprets the values as polar coordinates: magnitude and angle.
2348 *
2349 * '2@'.to_c.polar # => [2, 0.0] # Value before '@': magnitude only.
2350 * # Values before and after '@': magnitude and angle.
2351 * '2@1'.to_c.polar # => [2.0, 1.0]
2352 * "1.0@#{Math::PI/2}".to_c # => (0.0+1i)
2353 * "1.0@#{Math::PI}".to_c # => (-1+0.0i)
2354 * # Magnitude not given: defaults to zero.
2355 * '@'.to_c.polar # => [0, 0.0]
2356 * '@1'.to_c.polar # => [0, 0.0]
2357 *
2358 * '1.0@0'.to_c # => (1+0.0i)
2359 *
2360 * Note that in all cases, the suffixed character <tt>'i'</tt>
2361 * may instead be one of <tt>'I'</tt>, <tt>'j'</tt>, <tt>'J'</tt>,
2362 * with the same effect.
2363 *
2364 * See {Converting to Non-String}[rdoc-ref:String@Converting+to+Non--5CString].
2365 */
2366static VALUE
2367string_to_c(VALUE self)
2368{
2369 VALUE num;
2370
2371 rb_must_asciicompat(self);
2372
2373 (void)parse_comp(rb_str_fill_terminator(self, 1), FALSE, &num);
2374
2375 return num;
2376}
2377
2378static VALUE
2379to_complex(VALUE val)
2380{
2381 return rb_convert_type(val, T_COMPLEX, "Complex", "to_c");
2382}
2383
2384static VALUE
2385nucomp_convert(VALUE klass, VALUE a1, VALUE a2, int raise)
2386{
2387 if (NIL_P(a1) || NIL_P(a2)) {
2388 if (!raise) return Qnil;
2389 rb_cant_convert(Qnil, "Complex");
2390 }
2391
2392 if (RB_TYPE_P(a1, T_STRING)) {
2393 a1 = string_to_c_strict(a1, raise);
2394 if (NIL_P(a1)) return Qnil;
2395 }
2396
2397 if (RB_TYPE_P(a2, T_STRING)) {
2398 a2 = string_to_c_strict(a2, raise);
2399 if (NIL_P(a2)) return Qnil;
2400 }
2401
2402 if (RB_TYPE_P(a1, T_COMPLEX)) {
2403 {
2404 get_dat1(a1);
2405
2406 if (k_exact_zero_p(dat->imag))
2407 a1 = dat->real;
2408 }
2409 }
2410
2411 if (RB_TYPE_P(a2, T_COMPLEX)) {
2412 {
2413 get_dat1(a2);
2414
2415 if (k_exact_zero_p(dat->imag))
2416 a2 = dat->real;
2417 }
2418 }
2419
2420 if (RB_TYPE_P(a1, T_COMPLEX)) {
2421 if (UNDEF_P(a2) || (k_exact_zero_p(a2)))
2422 return a1;
2423 }
2424
2425 if (UNDEF_P(a2)) {
2426 if (k_numeric_p(a1) && !f_real_p(a1))
2427 return a1;
2428 /* should raise exception for consistency */
2429 if (!k_numeric_p(a1)) {
2430 if (!raise) {
2431 a1 = rb_protect(to_complex, a1, NULL);
2432 rb_set_errinfo(Qnil);
2433 return a1;
2434 }
2435 return to_complex(a1);
2436 }
2437 }
2438 else {
2439 if ((k_numeric_p(a1) && k_numeric_p(a2)) &&
2440 (!f_real_p(a1) || !f_real_p(a2)))
2441 return f_add(a1,
2442 f_mul(a2,
2443 f_complex_new_bang2(rb_cComplex, ZERO, ONE)));
2444 }
2445
2446 {
2447 int argc;
2448 VALUE argv2[2];
2449 argv2[0] = a1;
2450 if (UNDEF_P(a2)) {
2451 argv2[1] = Qnil;
2452 argc = 1;
2453 }
2454 else {
2455 if (!raise && !RB_INTEGER_TYPE_P(a2) && !RB_FLOAT_TYPE_P(a2) && !RB_TYPE_P(a2, T_RATIONAL))
2456 return Qnil;
2457 argv2[1] = a2;
2458 argc = 2;
2459 }
2460 return nucomp_s_new(argc, argv2, klass);
2461 }
2462}
2463
2464static VALUE
2465nucomp_s_convert(int argc, VALUE *argv, VALUE klass)
2466{
2467 VALUE a1, a2;
2468
2469 if (rb_scan_args(argc, argv, "11", &a1, &a2) == 1) {
2470 a2 = Qundef;
2471 }
2472
2473 return nucomp_convert(klass, a1, a2, TRUE);
2474}
2475
2476/*
2477 * call-seq:
2478 * abs2 -> real
2479 *
2480 * Returns the square of +self+.
2481 */
2482static VALUE
2483numeric_abs2(VALUE self)
2484{
2485 return f_mul(self, self);
2486}
2487
2488/*
2489 * call-seq:
2490 * arg -> 0 or Math::PI
2491 *
2492 * Returns zero if +self+ is positive, Math::PI otherwise.
2493 */
2494static VALUE
2495numeric_arg(VALUE self)
2496{
2497 if (f_positive_p(self))
2498 return INT2FIX(0);
2499 return DBL2NUM(M_PI);
2500}
2501
2502/*
2503 * call-seq:
2504 * rect -> array
2505 *
2506 * Returns array <tt>[self, 0]</tt>.
2507 */
2508static VALUE
2509numeric_rect(VALUE self)
2510{
2511 return rb_assoc_new(self, INT2FIX(0));
2512}
2513
2514/*
2515 * call-seq:
2516 * polar -> array
2517 *
2518 * Returns array <tt>[self.abs, self.arg]</tt>.
2519 */
2520static VALUE
2521numeric_polar(VALUE self)
2522{
2523 VALUE abs, arg;
2524
2525 if (RB_INTEGER_TYPE_P(self)) {
2526 abs = rb_int_abs(self);
2527 arg = numeric_arg(self);
2528 }
2529 else if (RB_FLOAT_TYPE_P(self)) {
2530 abs = rb_float_abs(self);
2531 arg = float_arg(self);
2532 }
2533 else if (RB_TYPE_P(self, T_RATIONAL)) {
2534 abs = rb_rational_abs(self);
2535 arg = numeric_arg(self);
2536 }
2537 else {
2538 abs = f_abs(self);
2539 arg = f_arg(self);
2540 }
2541 return rb_assoc_new(abs, arg);
2542}
2543
2544/*
2545 * call-seq:
2546 * arg -> 0 or Math::PI
2547 *
2548 * Returns 0 if +self+ is positive, Math::PI otherwise.
2549 */
2550static VALUE
2551float_arg(VALUE self)
2552{
2553 if (isnan(RFLOAT_VALUE(self)))
2554 return self;
2555 if (f_tpositive_p(self))
2556 return INT2FIX(0);
2557 return rb_const_get(rb_mMath, id_PI);
2558}
2559
2560/*
2561 * A \Complex object houses a pair of values,
2562 * given when the object is created as either <i>rectangular coordinates</i>
2563 * or <i>polar coordinates</i>.
2564 *
2565 * == Rectangular Coordinates
2566 *
2567 * The rectangular coordinates of a complex number
2568 * are called the _real_ and _imaginary_ parts;
2569 * see {Complex number definition}[https://en.wikipedia.org/wiki/Complex_number#Definition_and_basic_operations].
2570 *
2571 * You can create a \Complex object from rectangular coordinates with:
2572 *
2573 * - A {complex literal}[rdoc-ref:syntax/literals.rdoc@Complex+Literals].
2574 * - Method Complex.rect.
2575 * - Method Kernel#Complex, either with numeric arguments or with certain string arguments.
2576 * - Method String#to_c, for certain strings.
2577 *
2578 * Note that each of the stored parts may be a an instance one of the classes
2579 * Complex, Float, Integer, or Rational;
2580 * they may be retrieved:
2581 *
2582 * - Separately, with methods Complex#real and Complex#imaginary.
2583 * - Together, with method Complex#rect.
2584 *
2585 * The corresponding (computed) polar values may be retrieved:
2586 *
2587 * - Separately, with methods Complex#abs and Complex#arg.
2588 * - Together, with method Complex#polar.
2589 *
2590 * == Polar Coordinates
2591 *
2592 * The polar coordinates of a complex number
2593 * are called the _absolute_ and _argument_ parts;
2594 * see {Complex polar plane}[https://en.wikipedia.org/wiki/Complex_number#Polar_form].
2595 *
2596 * In this class, the argument part
2597 * in expressed {radians}[https://en.wikipedia.org/wiki/Radian]
2598 * (not {degrees}[https://en.wikipedia.org/wiki/Degree_(angle)]).
2599 *
2600 * You can create a \Complex object from polar coordinates with:
2601 *
2602 * - Method Complex.polar.
2603 * - Method Kernel#Complex, with certain string arguments.
2604 * - Method String#to_c, for certain strings.
2605 *
2606 * Note that each of the stored parts may be a an instance one of the classes
2607 * Complex, Float, Integer, or Rational;
2608 * they may be retrieved:
2609 *
2610 * - Separately, with methods Complex#abs and Complex#arg.
2611 * - Together, with method Complex#polar.
2612 *
2613 * The corresponding (computed) rectangular values may be retrieved:
2614 *
2615 * - Separately, with methods Complex#real and Complex#imag.
2616 * - Together, with method Complex#rect.
2617 *
2618 * == What's Here
2619 *
2620 * First, what's elsewhere:
2621 *
2622 * - Class \Complex inherits (directly or indirectly)
2623 * from classes {Numeric}[rdoc-ref:Numeric@Whats-Here]
2624 * and {Object}[rdoc-ref:Object@Whats-Here].
2625 * - Includes (indirectly) module {Comparable}[rdoc-ref:Comparable@Whats-Here].
2626 *
2627 * Here, class \Complex has methods for:
2628 *
2629 * === Creating \Complex Objects
2630 *
2631 * - ::polar: Returns a new \Complex object based on given polar coordinates.
2632 * - ::rect (and its alias ::rectangular):
2633 * Returns a new \Complex object based on given rectangular coordinates.
2634 *
2635 * === Querying
2636 *
2637 * - #abs (and its alias #magnitude): Returns the absolute value for +self+.
2638 * - #arg (and its aliases #angle and #phase):
2639 * Returns the argument (angle) for +self+ in radians.
2640 * - #denominator: Returns the denominator of +self+.
2641 * - #finite?: Returns whether both +self.real+ and +self.image+ are finite.
2642 * - #hash: Returns the integer hash value for +self+.
2643 * - #imag (and its alias #imaginary): Returns the imaginary value for +self+.
2644 * - #infinite?: Returns whether +self.real+ or +self.image+ is infinite.
2645 * - #numerator: Returns the numerator of +self+.
2646 * - #polar: Returns the array <tt>[self.abs, self.arg]</tt>.
2647 * - #inspect: Returns a string representation of +self+.
2648 * - #real: Returns the real value for +self+.
2649 * - #real?: Returns +false+; for compatibility with Numeric#real?.
2650 * - #rect (and its alias #rectangular):
2651 * Returns the array <tt>[self.real, self.imag]</tt>.
2652 *
2653 * === Comparing
2654 *
2655 * - #<=>: Returns whether +self+ is less than, equal to, or greater than the given argument.
2656 * - #==: Returns whether +self+ is equal to the given argument.
2657 *
2658 * === Converting
2659 *
2660 * - #rationalize: Returns a Rational object whose value is exactly
2661 * or approximately equivalent to that of <tt>self.real</tt>.
2662 * - #to_c: Returns +self+.
2663 * - #to_d: Returns the value as a BigDecimal object.
2664 * - #to_f: Returns the value of <tt>self.real</tt> as a Float, if possible.
2665 * - #to_i: Returns the value of <tt>self.real</tt> as an Integer, if possible.
2666 * - #to_r: Returns the value of <tt>self.real</tt> as a Rational, if possible.
2667 * - #to_s: Returns a string representation of +self+.
2668 *
2669 * === Performing Complex Arithmetic
2670 *
2671 * - #*: Returns the product of +self+ and the given numeric.
2672 * - #**: Returns +self+ raised to power of the given numeric.
2673 * - #+: Returns the sum of +self+ and the given numeric.
2674 * - #-: Returns the difference of +self+ and the given numeric.
2675 * - #-@: Returns the negation of +self+.
2676 * - #/: Returns the quotient of +self+ and the given numeric.
2677 * - #abs2: Returns square of the absolute value (magnitude) for +self+.
2678 * - #conj (and its alias #conjugate): Returns the conjugate of +self+.
2679 * - #fdiv: Returns <tt>Complex.rect(self.real/numeric, self.imag/numeric)</tt>.
2680 *
2681 * === Working with JSON
2682 *
2683 * - ::json_create: Returns a new \Complex object,
2684 * deserialized from the given serialized hash.
2685 * - #as_json: Returns a serialized hash constructed from +self+.
2686 * - #to_json: Returns a JSON string representing +self+.
2687 *
2688 * These methods are provided by the {JSON gem}[https://github.com/ruby/json]. To make these methods available:
2689 *
2690 * require 'json/add/complex'
2691 *
2692 */
2693void
2694Init_Complex(void)
2695{
2696 VALUE compat;
2697 id_abs = rb_intern_const("abs");
2698 id_arg = rb_intern_const("arg");
2699 id_denominator = rb_intern_const("denominator");
2700 id_numerator = rb_intern_const("numerator");
2701 id_real_p = rb_intern_const("real?");
2702 id_i_real = rb_intern_const("@real");
2703 id_i_imag = rb_intern_const("@image"); /* @image, not @imag */
2704 id_finite_p = rb_intern_const("finite?");
2705 id_infinite_p = rb_intern_const("infinite?");
2706 id_rationalize = rb_intern_const("rationalize");
2707 id_PI = rb_intern_const("PI");
2708
2710
2711 rb_define_alloc_func(rb_cComplex, nucomp_s_alloc);
2712 rb_undef_method(CLASS_OF(rb_cComplex), "allocate");
2713
2715
2716 rb_define_singleton_method(rb_cComplex, "rectangular", nucomp_s_new, -1);
2717 rb_define_singleton_method(rb_cComplex, "rect", nucomp_s_new, -1);
2718 rb_define_singleton_method(rb_cComplex, "polar", nucomp_s_polar, -1);
2719
2720 rb_define_global_function("Complex", nucomp_f_complex, -1);
2721
2722 rb_undef_methods_from(rb_cComplex, RCLASS_ORIGIN(rb_mComparable));
2725 rb_undef_method(rb_cComplex, "divmod");
2726 rb_undef_method(rb_cComplex, "floor");
2728 rb_undef_method(rb_cComplex, "modulo");
2729 rb_undef_method(rb_cComplex, "remainder");
2730 rb_undef_method(rb_cComplex, "round");
2732 rb_undef_method(rb_cComplex, "truncate");
2734
2735 rb_define_method(rb_cComplex, "real", rb_complex_real, 0);
2736 rb_define_method(rb_cComplex, "imaginary", rb_complex_imag, 0);
2737 rb_define_method(rb_cComplex, "imag", rb_complex_imag, 0);
2738
2739 rb_define_method(rb_cComplex, "-@", rb_complex_uminus, 0);
2740 rb_define_method(rb_cComplex, "+", rb_complex_plus, 1);
2741 rb_define_method(rb_cComplex, "-", rb_complex_minus, 1);
2742 rb_define_method(rb_cComplex, "*", rb_complex_mul, 1);
2743 rb_define_method(rb_cComplex, "/", rb_complex_div, 1);
2744 rb_define_method(rb_cComplex, "quo", nucomp_quo, 1);
2745 rb_define_method(rb_cComplex, "fdiv", nucomp_fdiv, 1);
2746 rb_define_method(rb_cComplex, "**", rb_complex_pow, 1);
2747
2748 rb_define_method(rb_cComplex, "==", nucomp_eqeq_p, 1);
2749 rb_define_method(rb_cComplex, "<=>", nucomp_cmp, 1);
2750 rb_define_method(rb_cComplex, "coerce", nucomp_coerce, 1);
2751
2752 rb_define_method(rb_cComplex, "abs", rb_complex_abs, 0);
2753 rb_define_method(rb_cComplex, "magnitude", rb_complex_abs, 0);
2754 rb_define_method(rb_cComplex, "abs2", nucomp_abs2, 0);
2755 rb_define_method(rb_cComplex, "arg", rb_complex_arg, 0);
2756 rb_define_method(rb_cComplex, "angle", rb_complex_arg, 0);
2757 rb_define_method(rb_cComplex, "phase", rb_complex_arg, 0);
2758 rb_define_method(rb_cComplex, "rectangular", nucomp_rect, 0);
2759 rb_define_method(rb_cComplex, "rect", nucomp_rect, 0);
2760 rb_define_method(rb_cComplex, "polar", nucomp_polar, 0);
2761 rb_define_method(rb_cComplex, "conjugate", rb_complex_conjugate, 0);
2762 rb_define_method(rb_cComplex, "conj", rb_complex_conjugate, 0);
2763
2764 rb_define_method(rb_cComplex, "real?", nucomp_real_p_m, 0);
2765
2766 rb_define_method(rb_cComplex, "numerator", nucomp_numerator, 0);
2767 rb_define_method(rb_cComplex, "denominator", nucomp_denominator, 0);
2768
2769 rb_define_method(rb_cComplex, "hash", nucomp_hash, 0);
2770 rb_define_method(rb_cComplex, "eql?", nucomp_eql_p, 1);
2771
2772 rb_define_method(rb_cComplex, "to_s", nucomp_to_s, 0);
2773 rb_define_method(rb_cComplex, "inspect", nucomp_inspect, 0);
2774
2775 rb_undef_method(rb_cComplex, "positive?");
2776 rb_undef_method(rb_cComplex, "negative?");
2777
2778 rb_define_method(rb_cComplex, "finite?", rb_complex_finite_p, 0);
2779 rb_define_method(rb_cComplex, "infinite?", rb_complex_infinite_p, 0);
2780
2781 rb_define_private_method(rb_cComplex, "marshal_dump", nucomp_marshal_dump, 0);
2782 /* :nodoc: */
2783 compat = rb_define_class_under(rb_cComplex, "compatible", rb_cObject);
2784 rb_define_private_method(compat, "marshal_load", nucomp_marshal_load, 1);
2785 rb_marshal_define_compat(rb_cComplex, compat, nucomp_dumper, nucomp_loader);
2786
2787 rb_define_method(rb_cComplex, "to_i", nucomp_to_i, 0);
2788 rb_define_method(rb_cComplex, "to_f", nucomp_to_f, 0);
2789 rb_define_method(rb_cComplex, "to_r", nucomp_to_r, 0);
2790 rb_define_method(rb_cComplex, "rationalize", nucomp_rationalize, -1);
2791 rb_define_method(rb_cComplex, "to_c", nucomp_to_c, 0);
2792 rb_define_method(rb_cNumeric, "to_c", numeric_to_c, 0);
2793
2794 rb_define_method(rb_cString, "to_c", string_to_c, 0);
2795
2796 rb_define_private_method(CLASS_OF(rb_cComplex), "convert", nucomp_s_convert, -1);
2797
2798 rb_define_method(rb_cNumeric, "abs2", numeric_abs2, 0);
2799 rb_define_method(rb_cNumeric, "arg", numeric_arg, 0);
2800 rb_define_method(rb_cNumeric, "angle", numeric_arg, 0);
2801 rb_define_method(rb_cNumeric, "phase", numeric_arg, 0);
2802 rb_define_method(rb_cNumeric, "rectangular", numeric_rect, 0);
2803 rb_define_method(rb_cNumeric, "rect", numeric_rect, 0);
2804 rb_define_method(rb_cNumeric, "polar", numeric_polar, 0);
2805
2806 rb_define_method(rb_cFloat, "arg", float_arg, 0);
2807 rb_define_method(rb_cFloat, "angle", float_arg, 0);
2808 rb_define_method(rb_cFloat, "phase", float_arg, 0);
2809
2810 /*
2811 * Equivalent
2812 * to <tt>Complex.rect(0, 1)</tt>:
2813 *
2814 * Complex::I # => (0+1i)
2815 *
2816 */
2817 rb_define_const(rb_cComplex, "I",
2818 f_complex_new_bang2(rb_cComplex, ZERO, ONE));
2819
2820#if !USE_FLONUM
2821 rb_vm_register_global_object(RFLOAT_0 = DBL2NUM(0.0));
2822#endif
2823
2824 rb_provide("complex.so"); /* for backward compatibility */
2825}
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
static int rb_isdigit(int c)
Our own locale-insensitive version of isdigit(3).
Definition ctype.h:302
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
#define rb_define_global_function(mid, func, arity)
Defines rb_mKernel #mid.
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1396
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition class.c:1427
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2581
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3061
#define T_COMPLEX
Old name of RUBY_T_COMPLEX.
Definition value_type.h:59
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition value_type.h:87
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition double.h:28
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1684
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
Definition value_type.h:76
#define NUM2DBL
Old name of rb_num2dbl.
Definition double.h:27
#define rb_usascii_str_new2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1681
#define FLONUM_P
Old name of RB_FLONUM_P.
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:405
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:406
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1431
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1427
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:467
VALUE rb_cRational
Rational class.
Definition rational.c:54
VALUE rb_convert_type(VALUE val, int type, const char *name, const char *mid)
Converts an object into another type.
Definition object.c:3235
VALUE rb_cComplex
Complex class.
Definition complex.c:40
VALUE rb_cObject
Object class.
Definition object.c:61
VALUE rb_mMath
Math module.
Definition math.c:28
VALUE rb_cInteger
Module class.
Definition numeric.c:199
double rb_str_to_dbl(VALUE str, int mode)
Identical to rb_cstr_to_dbl(), except it accepts a Ruby's string instead of C's.
Definition object.c:3651
VALUE rb_cNumeric
Numeric class.
Definition numeric.c:197
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:235
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:657
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:141
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:894
double rb_cstr_to_dbl(const char *str, int mode)
Converts a textual representation of a real number into a numeric, which is the nearest value that th...
Definition object.c:3607
VALUE rb_mComparable
Comparable module.
Definition compar.c:19
VALUE rb_cFloat
Float class.
Definition numeric.c:198
VALUE rb_String(VALUE val)
This is the logic behind Kernel#String.
Definition object.c:3877
VALUE rb_cString
String class.
Definition string.c:81
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1121
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
#define rb_complex_new2(x, y)
Just another name of rb_complex_new.
Definition complex.h:77
#define rb_complex_new1(x)
Shorthand of x+0i.
Definition complex.h:74
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
void rb_provide(const char *feature)
Declares that the given feature is already provided by someone else.
Definition load.c:695
VALUE rb_num_coerce_cmp(VALUE lhs, VALUE rhs, ID op)
Identical to rb_num_coerce_bin(), except for return values.
Definition numeric.c:485
VALUE rb_num_coerce_bin(VALUE lhs, VALUE rhs, ID op)
Coerced binary operation.
Definition numeric.c:478
VALUE rb_rational_new(VALUE num, VALUE den)
Constructs a Rational, with reduction.
Definition rational.c:1984
st_index_t rb_memhash(const void *ptr, long len)
This is a universal hash function.
Definition random.c:1791
void rb_must_asciicompat(VALUE obj)
Asserts that the given string's encoding is (Ruby's definition of) ASCII compatible.
Definition string.c:2792
VALUE rb_str_concat(VALUE dst, VALUE src)
Identical to rb_str_append(), except it also accepts an integer as a codepoint.
Definition string.c:4073
VALUE rb_const_get(VALUE space, ID name)
Identical to rb_const_defined(), except it returns the actual defined value.
Definition variable.c:3536
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2064
VALUE rb_ivar_get(VALUE obj, ID name)
Identical to rb_iv_get(), except it accepts the name as an ID instead of a C string.
Definition variable.c:1515
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:285
void rb_marshal_define_compat(VALUE newclass, VALUE oldclass, VALUE(*dumper)(VALUE), VALUE(*loader)(VALUE, VALUE))
Marshal format compatibility layer.
Definition marshal.c:138
void rb_copy_generic_ivar(VALUE clone, VALUE obj)
Copies the list of instance variables.
Definition variable.c:2275
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
#define RTEST
This is an old name of RB_TEST.
Internal header for Complex.
Definition complex.h:13
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition value.h:63
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static bool RB_FLOAT_TYPE_P(VALUE obj)
Queries if the object is an instance of rb_cFloat.
Definition value_type.h:264
static void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
Definition value_type.h:433
static bool rb_integer_type_p(VALUE obj)
Queries if the object is an instance of rb_cInteger.
Definition value_type.h:204
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376