Ruby: complex.c Source File

Ruby 4.0.6p0 (2026-07-14 revision 03b6d3f8898a28604fe6cb00eae3226b821168f4)

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