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