Tempfile document updated.
[ruby.git] / complex.c
blobf562ed316123c7f4b6f5ca642f35f3d3a25ebcd6
1 /*
2 complex.c: Coded by Tadayoshi Funaba 2008-2012
4 This implementation is based on Keiju Ishitsuka's Complex library
5 which is written in ruby.
6 */
8 #include "ruby/internal/config.h"
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
15 #include <ctype.h>
16 #include <math.h>
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"
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
36 static VALUE RFLOAT_0;
37 #endif
39 VALUE rb_cComplex;
41 static 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
54 #define fun1(n) \
55 inline static VALUE \
56 f_##n(VALUE x)\
58 return rb_funcall(x, id_##n, 0);\
61 #define fun2(n) \
62 inline static VALUE \
63 f_##n(VALUE x, VALUE y)\
65 return rb_funcall(x, id_##n, 1, y);\
68 #define PRESERVE_SIGNEDZERO
70 inline static VALUE
71 f_add(VALUE x, VALUE y)
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);
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);
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);
94 return rb_funcall(x, '+', 1, y);
97 inline static VALUE
98 f_div(VALUE x, VALUE y)
100 if (FIXNUM_P(y) && FIX2LONG(y) == 1)
101 return x;
102 return rb_funcall(x, '/', 1, y);
105 inline static int
106 f_gt_p(VALUE x, VALUE y)
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));
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;
119 return RTEST(rb_funcall(x, '>', 1, y));
122 inline static VALUE
123 f_mul(VALUE x, VALUE y)
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);
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);
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);
145 else if (LIKELY(rb_method_basic_definition_p(CLASS_OF(x), idMULT))) {
146 if (y == ONE) return x;
148 return rb_funcall(x, '*', 1, y);
151 inline static VALUE
152 f_sub(VALUE x, VALUE y)
154 if (FIXNUM_ZERO_P(y) &&
155 LIKELY(rb_method_basic_definition_p(CLASS_OF(x), idMINUS))) {
156 return x;
158 return rb_funcall(x, '-', 1, y);
161 inline static VALUE
162 f_abs(VALUE x)
164 if (RB_INTEGER_TYPE_P(x)) {
165 return rb_int_abs(x);
167 else if (RB_FLOAT_TYPE_P(x)) {
168 return rb_float_abs(x);
170 else if (RB_TYPE_P(x, T_RATIONAL)) {
171 return rb_rational_abs(x);
173 else if (RB_TYPE_P(x, T_COMPLEX)) {
174 return rb_complex_abs(x);
176 return rb_funcall(x, id_abs, 0);
179 static VALUE numeric_arg(VALUE self);
180 static VALUE float_arg(VALUE self);
182 inline static VALUE
183 f_arg(VALUE x)
185 if (RB_INTEGER_TYPE_P(x)) {
186 return numeric_arg(x);
188 else if (RB_FLOAT_TYPE_P(x)) {
189 return float_arg(x);
191 else if (RB_TYPE_P(x, T_RATIONAL)) {
192 return numeric_arg(x);
194 else if (RB_TYPE_P(x, T_COMPLEX)) {
195 return rb_complex_arg(x);
197 return rb_funcall(x, id_arg, 0);
200 inline static VALUE
201 f_numerator(VALUE x)
203 if (RB_TYPE_P(x, T_RATIONAL)) {
204 return RRATIONAL(x)->num;
206 if (RB_FLOAT_TYPE_P(x)) {
207 return rb_float_numerator(x);
209 return x;
212 inline static VALUE
213 f_denominator(VALUE x)
215 if (RB_TYPE_P(x, T_RATIONAL)) {
216 return RRATIONAL(x)->den;
218 if (RB_FLOAT_TYPE_P(x)) {
219 return rb_float_denominator(x);
221 return INT2FIX(1);
224 inline static VALUE
225 f_negate(VALUE x)
227 if (RB_INTEGER_TYPE_P(x)) {
228 return rb_int_uminus(x);
230 else if (RB_FLOAT_TYPE_P(x)) {
231 return rb_float_uminus(x);
233 else if (RB_TYPE_P(x, T_RATIONAL)) {
234 return rb_rational_uminus(x);
236 else if (RB_TYPE_P(x, T_COMPLEX)) {
237 return rb_complex_uminus(x);
239 return rb_funcall(x, id_negate, 0);
242 static bool nucomp_real_p(VALUE self);
244 static inline bool
245 f_real_p(VALUE x)
247 if (RB_INTEGER_TYPE_P(x)) {
248 return true;
250 else if (RB_FLOAT_TYPE_P(x)) {
251 return true;
253 else if (RB_TYPE_P(x, T_RATIONAL)) {
254 return true;
256 else if (RB_TYPE_P(x, T_COMPLEX)) {
257 return nucomp_real_p(x);
259 return rb_funcall(x, id_real_p, 0);
262 inline static VALUE
263 f_to_i(VALUE x)
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);
270 inline static VALUE
271 f_to_f(VALUE x)
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);
278 fun1(to_r)
280 inline static int
281 f_eqeq_p(VALUE x, VALUE y)
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);
290 fun2(expt)
291 fun2(fdiv)
293 static VALUE
294 f_quo(VALUE x, VALUE y)
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);
303 return rb_funcallv(x, id_quo, 1, &y);
306 inline static int
307 f_negative_p(VALUE x)
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);
318 #define f_positive_p(x) (!f_negative_p(x))
320 inline static bool
321 f_zero_p(VALUE x)
323 if (RB_FLOAT_TYPE_P(x)) {
324 return FLOAT_ZERO_P(x);
326 else if (RB_INTEGER_TYPE_P(x)) {
327 return FIXNUM_ZERO_P(x);
329 else if (RB_TYPE_P(x, T_RATIONAL)) {
330 const VALUE num = RRATIONAL(x)->num;
331 return FIXNUM_ZERO_P(num);
333 return rb_equal(x, ZERO) != 0;
336 #define f_nonzero_p(x) (!f_zero_p(x))
338 static inline bool
339 always_finite_type_p(VALUE x)
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));
346 inline static int
347 f_finite_p(VALUE x)
349 if (always_finite_type_p(x)) {
350 return TRUE;
352 else if (RB_FLOAT_TYPE_P(x)) {
353 return isfinite(RFLOAT_VALUE(x));
355 return RTEST(rb_funcallv(x, id_finite_p, 0, 0));
358 inline static int
359 f_infinite_p(VALUE x)
361 if (always_finite_type_p(x)) {
362 return FALSE;
364 else if (RB_FLOAT_TYPE_P(x)) {
365 return isinf(RFLOAT_VALUE(x));
367 return RTEST(rb_funcallv(x, id_infinite_p, 0, 0));
370 inline static int
371 f_kind_of_p(VALUE x, VALUE c)
373 return (int)rb_obj_is_kind_of(x, c);
376 inline static int
377 k_numeric_p(VALUE x)
379 return f_kind_of_p(x, rb_cNumeric);
382 #define k_exact_p(x) (!RB_FLOAT_TYPE_P(x))
384 #define k_exact_zero_p(x) (k_exact_p(x) && f_zero_p(x))
386 #define get_dat1(x) \
387 struct RComplex *dat = RCOMPLEX(x)
389 #define get_dat2(x,y) \
390 struct RComplex *adat = RCOMPLEX(x), *bdat = RCOMPLEX(y)
392 inline static VALUE
393 nucomp_s_new_internal(VALUE klass, VALUE real, VALUE imag)
395 NEWOBJ_OF(obj, struct RComplex, klass,
396 T_COMPLEX | (RGENGC_WB_PROTECTED_COMPLEX ? FL_WB_PROTECTED : 0), sizeof(struct RComplex), 0);
398 RCOMPLEX_SET_REAL(obj, real);
399 RCOMPLEX_SET_IMAG(obj, imag);
400 OBJ_FREEZE((VALUE)obj);
402 return (VALUE)obj;
405 static VALUE
406 nucomp_s_alloc(VALUE klass)
408 return nucomp_s_new_internal(klass, ZERO, ZERO);
411 inline static VALUE
412 f_complex_new_bang1(VALUE klass, VALUE x)
414 RUBY_ASSERT(!RB_TYPE_P(x, T_COMPLEX));
415 return nucomp_s_new_internal(klass, x, ZERO);
418 inline static VALUE
419 f_complex_new_bang2(VALUE klass, VALUE x, VALUE y)
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);
426 WARN_UNUSED_RESULT(inline static VALUE nucomp_real_check(VALUE num));
427 inline static VALUE
428 nucomp_real_check(VALUE num)
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;
438 if (!k_numeric_p(num) || !f_real_p(num))
439 rb_raise(rb_eTypeError, "not a real");
441 return num;
444 inline static VALUE
445 nucomp_s_canonicalize_internal(VALUE klass, VALUE real, VALUE imag)
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);
453 else if (!complex_r) {
454 get_dat1(imag);
456 return nucomp_s_new_internal(klass,
457 f_sub(real, dat->imag),
458 f_add(ZERO, dat->real));
460 else if (!complex_i) {
461 get_dat1(real);
463 return nucomp_s_new_internal(klass,
464 dat->real,
465 f_add(dat->imag, imag));
467 else {
468 get_dat2(real, imag);
470 return nucomp_s_new_internal(klass,
471 f_sub(adat->real, bdat->imag),
472 f_add(adat->imag, bdat->real));
477 * call-seq:
478 * Complex.rect(real, imag = 0) -> complex
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]:
486 * Complex.rect(3) # => (3+0i)
487 * Complex.rect(3, Math::PI) # => (3+3.141592653589793i)
488 * Complex.rect(-3, -Math::PI) # => (-3-3.141592653589793i)
490 * \Complex.rectangular is an alias for \Complex.rect.
492 static VALUE
493 nucomp_s_new(int argc, VALUE *argv, VALUE klass)
495 VALUE real, imag;
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;
508 return nucomp_s_new_internal(klass, real, imag);
511 inline static VALUE
512 f_complex_new2(VALUE klass, VALUE x, VALUE y)
514 if (RB_TYPE_P(x, T_COMPLEX)) {
515 get_dat1(x);
516 x = dat->real;
517 y = f_add(dat->imag, y);
519 return nucomp_s_canonicalize_internal(klass, x, y);
522 static VALUE nucomp_convert(VALUE klass, VALUE a1, VALUE a2, int raise);
523 static VALUE nucomp_s_convert(int argc, VALUE *argv, VALUE klass);
526 * call-seq:
527 * Complex(real, imag = 0, exception: true) -> complex or nil
528 * Complex(s, exception: true) -> complex or nil
530 * Returns a new \Complex object if the arguments are valid;
531 * otherwise raises an exception if +exception+ is +true+;
532 * otherwise returns +nil+.
534 * With Numeric arguments +real+ and +imag+,
535 * returns <tt>Complex.rect(real, imag)</tt> if the arguments are valid.
537 * With string argument +s+, returns a new \Complex object if the argument is valid;
538 * the string may have:
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]:
544 * - Sign-separated real and imaginary numeric substrings
545 * (with trailing character <tt>'i'</tt>):
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)
553 * - Real-only numeric string (without trailing character <tt>'i'</tt>):
555 * Complex('1') # => (1+0i)
556 * Complex('+1') # => (1+0i)
557 * Complex('-1') # => (-1+0i)
559 * - Imaginary-only numeric string (with trailing character <tt>'i'</tt>):
561 * Complex('1i') # => (0+1i)
562 * Complex('+1i') # => (0+1i)
563 * Complex('-1i') # => (0-1i)
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]:
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)
576 static VALUE
577 nucomp_f_complex(int argc, VALUE *argv, VALUE klass)
579 VALUE a1, a2, opts = Qnil;
580 int raise = TRUE;
582 if (rb_scan_args(argc, argv, "11:", &a1, &a2, &opts) == 1) {
583 a2 = Qundef;
585 if (!NIL_P(opts)) {
586 raise = rb_opts_exception_p(opts, raise);
588 if (argc > 0 && CLASS_OF(a1) == rb_cComplex && UNDEF_P(a2)) {
589 return a1;
591 return nucomp_convert(rb_cComplex, a1, a2, raise);
594 #define imp1(n) \
595 inline static VALUE \
596 m_##n##_bang(VALUE x)\
598 return rb_math_##n(x);\
601 imp1(cos)
602 imp1(cosh)
603 imp1(exp)
605 static VALUE
606 m_log_bang(VALUE x)
608 return rb_math_log(1, &x);
611 imp1(sin)
612 imp1(sinh)
614 static VALUE
615 m_cos(VALUE x)
617 if (!RB_TYPE_P(x, T_COMPLEX))
618 return m_cos_bang(x);
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)));
629 static VALUE
630 m_sin(VALUE x)
632 if (!RB_TYPE_P(x, T_COMPLEX))
633 return m_sin_bang(x);
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)));
644 static VALUE
645 f_complex_polar_real(VALUE klass, VALUE x, VALUE y)
647 if (f_zero_p(x) || f_zero_p(y)) {
648 return nucomp_s_new_internal(klass, x, RFLOAT_0);
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;
656 else if (arg == M_PI_2) {
657 y = x;
658 x = RFLOAT_0;
660 else if (arg == M_PI_2+M_PI) {
661 y = f_negate(x);
662 x = RFLOAT_0;
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);
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));
675 return nucomp_s_new_internal(klass, x, y);
677 return nucomp_s_canonicalize_internal(klass,
678 f_mul(x, m_cos(y)),
679 f_mul(x, m_sin(y)));
682 static VALUE
683 f_complex_polar(VALUE klass, VALUE x, VALUE y)
685 x = nucomp_real_check(x);
686 y = nucomp_real_check(y);
687 return f_complex_polar_real(klass, x, y);
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
702 rb_dbl_complex_new_polar_pi(double abs, double ang)
704 double fi;
705 const double fr = modf(ang, &fi);
706 int pos = fr == +0.5;
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));
712 else if (fr == 0.0) {
713 if (modf(fi / 2.0, &fi) != 0.0) abs = -abs;
714 return DBL2NUM(abs);
716 else {
717 const double real = abs * cospi(ang), imag = abs * sinpi(ang);
718 return rb_complex_new(DBL2NUM(real), DBL2NUM(imag));
723 * call-seq:
724 * Complex.polar(abs, arg = 0) -> complex
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]:
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)
738 static VALUE
739 nucomp_s_polar(int argc, VALUE *argv, VALUE klass)
741 VALUE abs, arg;
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);
748 else {
749 arg = ZERO;
751 return f_complex_polar_real(klass, abs, arg);
755 * call-seq:
756 * real -> numeric
758 * Returns the real value for +self+:
760 * Complex.rect(7).real # => 7
761 * Complex.rect(9, -4).real # => 9
763 * If +self+ was created with
764 * {polar coordinates}[rdoc-ref:Complex@Polar+Coordinates], the returned value
765 * is computed, and may be inexact:
767 * Complex.polar(1, Math::PI/4).real # => 0.7071067811865476 # Square root of 2.
770 VALUE
771 rb_complex_real(VALUE self)
773 get_dat1(self);
774 return dat->real;
778 * call-seq:
779 * imag -> numeric
781 * Returns the imaginary value for +self+:
783 * Complex.rect(7).imag # => 0
784 * Complex.rect(9, -4).imag # => -4
786 * If +self+ was created with
787 * {polar coordinates}[rdoc-ref:Complex@Polar+Coordinates], the returned value
788 * is computed, and may be inexact:
790 * Complex.polar(1, Math::PI/4).imag # => 0.7071067811865476 # Square root of 2.
793 VALUE
794 rb_complex_imag(VALUE self)
796 get_dat1(self);
797 return dat->imag;
801 * call-seq:
802 * -complex -> new_complex
804 * Returns the negation of +self+, which is the negation of each of its parts:
806 * -Complex.rect(1, 2) # => (-1-2i)
807 * -Complex.rect(-1, -2) # => (1+2i)
810 VALUE
811 rb_complex_uminus(VALUE self)
813 get_dat1(self);
814 return f_complex_new2(CLASS_OF(self),
815 f_negate(dat->real), f_negate(dat->imag));
819 * call-seq:
820 * complex + numeric -> new_complex
822 * Returns the sum of +self+ and +numeric+:
824 * Complex.rect(2, 3) + Complex.rect(2, 3) # => (4+6i)
825 * Complex.rect(900) + Complex.rect(1) # => (901+0i)
826 * Complex.rect(-2, 9) + Complex.rect(-9, 2) # => (-11+11i)
827 * Complex.rect(9, 8) + 4 # => (13+8i)
828 * Complex.rect(20, 9) + 9.8 # => (29.8+9i)
831 VALUE
832 rb_complex_plus(VALUE self, VALUE other)
834 if (RB_TYPE_P(other, T_COMPLEX)) {
835 VALUE real, imag;
837 get_dat2(self, other);
839 real = f_add(adat->real, bdat->real);
840 imag = f_add(adat->imag, bdat->imag);
842 return f_complex_new2(CLASS_OF(self), real, imag);
844 if (k_numeric_p(other) && f_real_p(other)) {
845 get_dat1(self);
847 return f_complex_new2(CLASS_OF(self),
848 f_add(dat->real, other), dat->imag);
850 return rb_num_coerce_bin(self, other, '+');
854 * call-seq:
855 * complex - numeric -> new_complex
857 * Returns the difference of +self+ and +numeric+:
859 * Complex.rect(2, 3) - Complex.rect(2, 3) # => (0+0i)
860 * Complex.rect(900) - Complex.rect(1) # => (899+0i)
861 * Complex.rect(-2, 9) - Complex.rect(-9, 2) # => (7+7i)
862 * Complex.rect(9, 8) - 4 # => (5+8i)
863 * Complex.rect(20, 9) - 9.8 # => (10.2+9i)
866 VALUE
867 rb_complex_minus(VALUE self, VALUE other)
869 if (RB_TYPE_P(other, T_COMPLEX)) {
870 VALUE real, imag;
872 get_dat2(self, other);
874 real = f_sub(adat->real, bdat->real);
875 imag = f_sub(adat->imag, bdat->imag);
877 return f_complex_new2(CLASS_OF(self), real, imag);
879 if (k_numeric_p(other) && f_real_p(other)) {
880 get_dat1(self);
882 return f_complex_new2(CLASS_OF(self),
883 f_sub(dat->real, other), dat->imag);
885 return rb_num_coerce_bin(self, other, '-');
888 static VALUE
889 safe_mul(VALUE a, VALUE b, bool az, bool bz)
891 double v;
892 if (!az && bz && RB_FLOAT_TYPE_P(a) && (v = RFLOAT_VALUE(a), !isnan(v))) {
893 a = signbit(v) ? DBL2NUM(-1.0) : DBL2NUM(1.0);
895 if (!bz && az && RB_FLOAT_TYPE_P(b) && (v = RFLOAT_VALUE(b), !isnan(v))) {
896 b = signbit(v) ? DBL2NUM(-1.0) : DBL2NUM(1.0);
898 return f_mul(a, b);
901 static void
902 comp_mul(VALUE areal, VALUE aimag, VALUE breal, VALUE bimag, VALUE *real, VALUE *imag)
904 bool arzero = f_zero_p(areal);
905 bool aizero = f_zero_p(aimag);
906 bool brzero = f_zero_p(breal);
907 bool bizero = f_zero_p(bimag);
908 *real = f_sub(safe_mul(areal, breal, arzero, brzero),
909 safe_mul(aimag, bimag, aizero, bizero));
910 *imag = f_add(safe_mul(areal, bimag, arzero, bizero),
911 safe_mul(aimag, breal, aizero, brzero));
915 * call-seq:
916 * complex * numeric -> new_complex
918 * Returns the product of +self+ and +numeric+:
920 * Complex.rect(2, 3) * Complex.rect(2, 3) # => (-5+12i)
921 * Complex.rect(900) * Complex.rect(1) # => (900+0i)
922 * Complex.rect(-2, 9) * Complex.rect(-9, 2) # => (0-85i)
923 * Complex.rect(9, 8) * 4 # => (36+32i)
924 * Complex.rect(20, 9) * 9.8 # => (196.0+88.2i)
927 VALUE
928 rb_complex_mul(VALUE self, VALUE other)
930 if (RB_TYPE_P(other, T_COMPLEX)) {
931 VALUE real, imag;
932 get_dat2(self, other);
934 comp_mul(adat->real, adat->imag, bdat->real, bdat->imag, &real, &imag);
936 return f_complex_new2(CLASS_OF(self), real, imag);
938 if (k_numeric_p(other) && f_real_p(other)) {
939 get_dat1(self);
941 return f_complex_new2(CLASS_OF(self),
942 f_mul(dat->real, other),
943 f_mul(dat->imag, other));
945 return rb_num_coerce_bin(self, other, '*');
948 inline static VALUE
949 f_divide(VALUE self, VALUE other,
950 VALUE (*func)(VALUE, VALUE), ID id)
952 if (RB_TYPE_P(other, T_COMPLEX)) {
953 VALUE r, n, x, y;
954 int flo;
955 get_dat2(self, other);
957 flo = (RB_FLOAT_TYPE_P(adat->real) || RB_FLOAT_TYPE_P(adat->imag) ||
958 RB_FLOAT_TYPE_P(bdat->real) || RB_FLOAT_TYPE_P(bdat->imag));
960 if (f_gt_p(f_abs(bdat->real), f_abs(bdat->imag))) {
961 r = (*func)(bdat->imag, bdat->real);
962 n = f_mul(bdat->real, f_add(ONE, f_mul(r, r)));
963 x = (*func)(f_add(adat->real, f_mul(adat->imag, r)), n);
964 y = (*func)(f_sub(adat->imag, f_mul(adat->real, r)), n);
966 else {
967 r = (*func)(bdat->real, bdat->imag);
968 n = f_mul(bdat->imag, f_add(ONE, f_mul(r, r)));
969 x = (*func)(f_add(f_mul(adat->real, r), adat->imag), n);
970 y = (*func)(f_sub(f_mul(adat->imag, r), adat->real), n);
972 if (!flo) {
973 x = rb_rational_canonicalize(x);
974 y = rb_rational_canonicalize(y);
976 return f_complex_new2(CLASS_OF(self), x, y);
978 if (k_numeric_p(other) && f_real_p(other)) {
979 VALUE x, y;
980 get_dat1(self);
981 x = rb_rational_canonicalize((*func)(dat->real, other));
982 y = rb_rational_canonicalize((*func)(dat->imag, other));
983 return f_complex_new2(CLASS_OF(self), x, y);
985 return rb_num_coerce_bin(self, other, id);
988 #define rb_raise_zerodiv() rb_raise(rb_eZeroDivError, "divided by 0")
991 * call-seq:
992 * complex / numeric -> new_complex
994 * Returns the quotient of +self+ and +numeric+:
996 * Complex.rect(2, 3) / Complex.rect(2, 3) # => (1+0i)
997 * Complex.rect(900) / Complex.rect(1) # => (900+0i)
998 * Complex.rect(-2, 9) / Complex.rect(-9, 2) # => ((36/85)-(77/85)*i)
999 * Complex.rect(9, 8) / 4 # => ((9/4)+2i)
1000 * Complex.rect(20, 9) / 9.8 # => (2.0408163265306123+0.9183673469387754i)
1003 VALUE
1004 rb_complex_div(VALUE self, VALUE other)
1006 return f_divide(self, other, f_quo, id_quo);
1009 #define nucomp_quo rb_complex_div
1012 * call-seq:
1013 * fdiv(numeric) -> new_complex
1015 * Returns <tt>Complex.rect(self.real/numeric, self.imag/numeric)</tt>:
1017 * Complex.rect(11, 22).fdiv(3) # => (3.6666666666666665+7.333333333333333i)
1020 static VALUE
1021 nucomp_fdiv(VALUE self, VALUE other)
1023 return f_divide(self, other, f_fdiv, id_fdiv);
1026 inline static VALUE
1027 f_reciprocal(VALUE x)
1029 return f_quo(ONE, x);
1032 static VALUE
1033 zero_for(VALUE x)
1035 if (RB_FLOAT_TYPE_P(x))
1036 return DBL2NUM(0);
1037 if (RB_TYPE_P(x, T_RATIONAL))
1038 return rb_rational_new(INT2FIX(0), INT2FIX(1));
1040 return INT2FIX(0);
1043 static VALUE
1044 complex_pow_for_special_angle(VALUE self, VALUE other)
1046 if (!rb_integer_type_p(other)) {
1047 return Qundef;
1050 get_dat1(self);
1051 VALUE x = Qundef;
1052 int dir;
1053 if (f_zero_p(dat->imag)) {
1054 x = dat->real;
1055 dir = 0;
1057 else if (f_zero_p(dat->real)) {
1058 x = dat->imag;
1059 dir = 2;
1061 else if (f_eqeq_p(dat->real, dat->imag)) {
1062 x = dat->real;
1063 dir = 1;
1065 else if (f_eqeq_p(dat->real, f_negate(dat->imag))) {
1066 x = dat->imag;
1067 dir = 3;
1068 } else {
1069 dir = 0;
1072 if (UNDEF_P(x)) return x;
1074 if (f_negative_p(x)) {
1075 x = f_negate(x);
1076 dir += 4;
1079 VALUE zx;
1080 if (dir % 2 == 0) {
1081 zx = rb_num_pow(x, other);
1083 else {
1084 zx = rb_num_pow(
1085 rb_funcall(rb_int_mul(TWO, x), '*', 1, x),
1086 rb_int_div(other, TWO)
1088 if (rb_int_odd_p(other)) {
1089 zx = rb_funcall(zx, '*', 1, x);
1092 static const int dirs[][2] = {
1093 {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}
1095 int z_dir = FIX2INT(rb_int_modulo(rb_int_mul(INT2FIX(dir), other), INT2FIX(8)));
1097 VALUE zr = Qfalse, zi = Qfalse;
1098 switch (dirs[z_dir][0]) {
1099 case 0: zr = zero_for(zx); break;
1100 case 1: zr = zx; break;
1101 case -1: zr = f_negate(zx); break;
1103 switch (dirs[z_dir][1]) {
1104 case 0: zi = zero_for(zx); break;
1105 case 1: zi = zx; break;
1106 case -1: zi = f_negate(zx); break;
1108 return nucomp_s_new_internal(CLASS_OF(self), zr, zi);
1113 * call-seq:
1114 * complex ** numeric -> new_complex
1116 * Returns +self+ raised to power +numeric+:
1118 * Complex.rect(0, 1) ** 2 # => (-1+0i)
1119 * Complex.rect(-8) ** Rational(1, 3) # => (1.0000000000000002+1.7320508075688772i)
1122 VALUE
1123 rb_complex_pow(VALUE self, VALUE other)
1125 if (k_numeric_p(other) && k_exact_zero_p(other))
1126 return f_complex_new_bang1(CLASS_OF(self), ONE);
1128 if (RB_TYPE_P(other, T_RATIONAL) && RRATIONAL(other)->den == LONG2FIX(1))
1129 other = RRATIONAL(other)->num; /* c14n */
1131 if (RB_TYPE_P(other, T_COMPLEX)) {
1132 get_dat1(other);
1134 if (k_exact_zero_p(dat->imag))
1135 other = dat->real; /* c14n */
1138 if (other == ONE) {
1139 get_dat1(self);
1140 return nucomp_s_new_internal(CLASS_OF(self), dat->real, dat->imag);
1143 VALUE result = complex_pow_for_special_angle(self, other);
1144 if (!UNDEF_P(result)) return result;
1146 if (RB_TYPE_P(other, T_COMPLEX)) {
1147 VALUE r, theta, nr, ntheta;
1149 get_dat1(other);
1151 r = f_abs(self);
1152 theta = f_arg(self);
1154 nr = m_exp_bang(f_sub(f_mul(dat->real, m_log_bang(r)),
1155 f_mul(dat->imag, theta)));
1156 ntheta = f_add(f_mul(theta, dat->real),
1157 f_mul(dat->imag, m_log_bang(r)));
1158 return f_complex_polar(CLASS_OF(self), nr, ntheta);
1160 if (FIXNUM_P(other)) {
1161 long n = FIX2LONG(other);
1162 if (n == 0) {
1163 return nucomp_s_new_internal(CLASS_OF(self), ONE, ZERO);
1165 if (n < 0) {
1166 self = f_reciprocal(self);
1167 other = rb_int_uminus(other);
1168 n = -n;
1171 get_dat1(self);
1172 VALUE xr = dat->real, xi = dat->imag, zr = xr, zi = xi;
1174 if (f_zero_p(xi)) {
1175 zr = rb_num_pow(zr, other);
1177 else if (f_zero_p(xr)) {
1178 zi = rb_num_pow(zi, other);
1179 if (n & 2) zi = f_negate(zi);
1180 if (!(n & 1)) {
1181 VALUE tmp = zr;
1182 zr = zi;
1183 zi = tmp;
1186 else {
1187 while (--n) {
1188 long q, r;
1190 for (; q = n / 2, r = n % 2, r == 0; n = q) {
1191 VALUE tmp = f_sub(f_mul(xr, xr), f_mul(xi, xi));
1192 xi = f_mul(f_mul(TWO, xr), xi);
1193 xr = tmp;
1195 comp_mul(zr, zi, xr, xi, &zr, &zi);
1198 return nucomp_s_new_internal(CLASS_OF(self), zr, zi);
1201 if (k_numeric_p(other) && f_real_p(other)) {
1202 VALUE r, theta;
1204 if (RB_BIGNUM_TYPE_P(other))
1205 rb_warn("in a**b, b may be too big");
1207 r = f_abs(self);
1208 theta = f_arg(self);
1210 return f_complex_polar(CLASS_OF(self), f_expt(r, other),
1211 f_mul(theta, other));
1213 return rb_num_coerce_bin(self, other, id_expt);
1217 * call-seq:
1218 * complex == object -> true or false
1220 * Returns +true+ if <tt>self.real == object.real</tt>
1221 * and <tt>self.imag == object.imag</tt>:
1223 * Complex.rect(2, 3) == Complex.rect(2.0, 3.0) # => true
1226 static VALUE
1227 nucomp_eqeq_p(VALUE self, VALUE other)
1229 if (RB_TYPE_P(other, T_COMPLEX)) {
1230 get_dat2(self, other);
1232 return RBOOL(f_eqeq_p(adat->real, bdat->real) &&
1233 f_eqeq_p(adat->imag, bdat->imag));
1235 if (k_numeric_p(other) && f_real_p(other)) {
1236 get_dat1(self);
1238 return RBOOL(f_eqeq_p(dat->real, other) && f_zero_p(dat->imag));
1240 return RBOOL(f_eqeq_p(other, self));
1243 static bool
1244 nucomp_real_p(VALUE self)
1246 get_dat1(self);
1247 return f_zero_p(dat->imag);
1251 * call-seq:
1252 * complex <=> object -> -1, 0, 1, or nil
1254 * Returns:
1256 * - <tt>self.real <=> object.real</tt> if both of the following are true:
1258 * - <tt>self.imag == 0</tt>.
1259 * - <tt>object.imag == 0</tt>. # Always true if object is numeric but not complex.
1261 * - +nil+ otherwise.
1263 * Examples:
1265 * Complex.rect(2) <=> 3 # => -1
1266 * Complex.rect(2) <=> 2 # => 0
1267 * Complex.rect(2) <=> 1 # => 1
1268 * Complex.rect(2, 1) <=> 1 # => nil # self.imag not zero.
1269 * Complex.rect(1) <=> Complex.rect(1, 1) # => nil # object.imag not zero.
1270 * Complex.rect(1) <=> 'Foo' # => nil # object.imag not defined.
1273 static VALUE
1274 nucomp_cmp(VALUE self, VALUE other)
1276 if (!k_numeric_p(other)) {
1277 return rb_num_coerce_cmp(self, other, idCmp);
1279 if (!nucomp_real_p(self)) {
1280 return Qnil;
1282 if (RB_TYPE_P(other, T_COMPLEX)) {
1283 if (nucomp_real_p(other)) {
1284 get_dat2(self, other);
1285 return rb_funcall(adat->real, idCmp, 1, bdat->real);
1288 else {
1289 get_dat1(self);
1290 if (f_real_p(other)) {
1291 return rb_funcall(dat->real, idCmp, 1, other);
1293 else {
1294 return rb_num_coerce_cmp(dat->real, other, idCmp);
1297 return Qnil;
1300 /* :nodoc: */
1301 static VALUE
1302 nucomp_coerce(VALUE self, VALUE other)
1304 if (RB_TYPE_P(other, T_COMPLEX))
1305 return rb_assoc_new(other, self);
1306 if (k_numeric_p(other) && f_real_p(other))
1307 return rb_assoc_new(f_complex_new_bang1(CLASS_OF(self), other), self);
1309 rb_raise(rb_eTypeError, "%"PRIsVALUE" can't be coerced into %"PRIsVALUE,
1310 rb_obj_class(other), rb_obj_class(self));
1311 return Qnil;
1315 * call-seq:
1316 * abs -> float
1318 * Returns the absolute value (magnitude) for +self+;
1319 * see {polar coordinates}[rdoc-ref:Complex@Polar+Coordinates]:
1321 * Complex.polar(-1, 0).abs # => 1.0
1323 * If +self+ was created with
1324 * {rectangular coordinates}[rdoc-ref:Complex@Rectangular+Coordinates], the returned value
1325 * is computed, and may be inexact:
1327 * Complex.rectangular(1, 1).abs # => 1.4142135623730951 # The square root of 2.
1330 VALUE
1331 rb_complex_abs(VALUE self)
1333 get_dat1(self);
1335 if (f_zero_p(dat->real)) {
1336 VALUE a = f_abs(dat->imag);
1337 if (RB_FLOAT_TYPE_P(dat->real) && !RB_FLOAT_TYPE_P(dat->imag))
1338 a = f_to_f(a);
1339 return a;
1341 if (f_zero_p(dat->imag)) {
1342 VALUE a = f_abs(dat->real);
1343 if (!RB_FLOAT_TYPE_P(dat->real) && RB_FLOAT_TYPE_P(dat->imag))
1344 a = f_to_f(a);
1345 return a;
1347 return rb_math_hypot(dat->real, dat->imag);
1351 * call-seq:
1352 * abs2 -> float
1354 * Returns square of the absolute value (magnitude) for +self+;
1355 * see {polar coordinates}[rdoc-ref:Complex@Polar+Coordinates]:
1357 * Complex.polar(2, 2).abs2 # => 4.0
1359 * If +self+ was created with
1360 * {rectangular coordinates}[rdoc-ref:Complex@Rectangular+Coordinates], the returned value
1361 * is computed, and may be inexact:
1363 * Complex.rectangular(1.0/3, 1.0/3).abs2 # => 0.2222222222222222
1366 static VALUE
1367 nucomp_abs2(VALUE self)
1369 get_dat1(self);
1370 return f_add(f_mul(dat->real, dat->real),
1371 f_mul(dat->imag, dat->imag));
1375 * call-seq:
1376 * arg -> float
1378 * Returns the argument (angle) for +self+ in radians;
1379 * see {polar coordinates}[rdoc-ref:Complex@Polar+Coordinates]:
1381 * Complex.polar(3, Math::PI/2).arg # => 1.57079632679489660
1383 * If +self+ was created with
1384 * {rectangular coordinates}[rdoc-ref:Complex@Rectangular+Coordinates], the returned value
1385 * is computed, and may be inexact:
1387 * Complex.polar(1, 1.0/3).arg # => 0.33333333333333326
1390 VALUE
1391 rb_complex_arg(VALUE self)
1393 get_dat1(self);
1394 return rb_math_atan2(dat->imag, dat->real);
1398 * call-seq:
1399 * rect -> array
1401 * Returns the array <tt>[self.real, self.imag]</tt>:
1403 * Complex.rect(1, 2).rect # => [1, 2]
1405 * See {Rectangular Coordinates}[rdoc-ref:Complex@Rectangular+Coordinates].
1407 * If +self+ was created with
1408 * {polar coordinates}[rdoc-ref:Complex@Polar+Coordinates], the returned value
1409 * is computed, and may be inexact:
1411 * Complex.polar(1.0, 1.0).rect # => [0.5403023058681398, 0.8414709848078965]
1414 * Complex#rectangular is an alias for Complex#rect.
1416 static VALUE
1417 nucomp_rect(VALUE self)
1419 get_dat1(self);
1420 return rb_assoc_new(dat->real, dat->imag);
1424 * call-seq:
1425 * polar -> array
1427 * Returns the array <tt>[self.abs, self.arg]</tt>:
1429 * Complex.polar(1, 2).polar # => [1.0, 2.0]
1431 * See {Polar Coordinates}[rdoc-ref:Complex@Polar+Coordinates].
1433 * If +self+ was created with
1434 * {rectangular coordinates}[rdoc-ref:Complex@Rectangular+Coordinates], the returned value
1435 * is computed, and may be inexact:
1437 * Complex.rect(1, 1).polar # => [1.4142135623730951, 0.7853981633974483]
1440 static VALUE
1441 nucomp_polar(VALUE self)
1443 return rb_assoc_new(f_abs(self), f_arg(self));
1447 * call-seq:
1448 * conj -> complex
1450 * Returns the conjugate of +self+, <tt>Complex.rect(self.imag, self.real)</tt>:
1452 * Complex.rect(1, 2).conj # => (1-2i)
1455 VALUE
1456 rb_complex_conjugate(VALUE self)
1458 get_dat1(self);
1459 return f_complex_new2(CLASS_OF(self), dat->real, f_negate(dat->imag));
1463 * call-seq:
1464 * real? -> false
1466 * Returns +false+; for compatibility with Numeric#real?.
1468 static VALUE
1469 nucomp_real_p_m(VALUE self)
1471 return Qfalse;
1475 * call-seq:
1476 * denominator -> integer
1478 * Returns the denominator of +self+, which is
1479 * the {least common multiple}[https://en.wikipedia.org/wiki/Least_common_multiple]
1480 * of <tt>self.real.denominator</tt> and <tt>self.imag.denominator</tt>:
1482 * Complex.rect(Rational(1, 2), Rational(2, 3)).denominator # => 6
1484 * Note that <tt>n.denominator</tt> of a non-rational numeric is +1+.
1486 * Related: Complex#numerator.
1488 static VALUE
1489 nucomp_denominator(VALUE self)
1491 get_dat1(self);
1492 return rb_lcm(f_denominator(dat->real), f_denominator(dat->imag));
1496 * call-seq:
1497 * numerator -> new_complex
1499 * Returns the \Complex object created from the numerators
1500 * of the real and imaginary parts of +self+,
1501 * after converting each part to the
1502 * {lowest common denominator}[https://en.wikipedia.org/wiki/Lowest_common_denominator]
1503 * of the two:
1505 * c = Complex.rect(Rational(2, 3), Rational(3, 4)) # => ((2/3)+(3/4)*i)
1506 * c.numerator # => (8+9i)
1508 * In this example, the lowest common denominator of the two parts is 12;
1509 * the two converted parts may be thought of as \Rational(8, 12) and \Rational(9, 12),
1510 * whose numerators, respectively, are 8 and 9;
1511 * so the returned value of <tt>c.numerator</tt> is <tt>Complex.rect(8, 9)</tt>.
1513 * Related: Complex#denominator.
1515 static VALUE
1516 nucomp_numerator(VALUE self)
1518 VALUE cd;
1520 get_dat1(self);
1522 cd = nucomp_denominator(self);
1523 return f_complex_new2(CLASS_OF(self),
1524 f_mul(f_numerator(dat->real),
1525 f_div(cd, f_denominator(dat->real))),
1526 f_mul(f_numerator(dat->imag),
1527 f_div(cd, f_denominator(dat->imag))));
1530 /* :nodoc: */
1531 st_index_t
1532 rb_complex_hash(VALUE self)
1534 st_index_t v, h[2];
1535 VALUE n;
1537 get_dat1(self);
1538 n = rb_hash(dat->real);
1539 h[0] = NUM2LONG(n);
1540 n = rb_hash(dat->imag);
1541 h[1] = NUM2LONG(n);
1542 v = rb_memhash(h, sizeof(h));
1543 return v;
1547 * :call-seq:
1548 * hash -> integer
1550 * Returns the integer hash value for +self+.
1552 * Two \Complex objects created from the same values will have the same hash value
1553 * (and will compare using #eql?):
1555 * Complex.rect(1, 2).hash == Complex.rect(1, 2).hash # => true
1558 static VALUE
1559 nucomp_hash(VALUE self)
1561 return ST2FIX(rb_complex_hash(self));
1564 /* :nodoc: */
1565 static VALUE
1566 nucomp_eql_p(VALUE self, VALUE other)
1568 if (RB_TYPE_P(other, T_COMPLEX)) {
1569 get_dat2(self, other);
1571 return RBOOL((CLASS_OF(adat->real) == CLASS_OF(bdat->real)) &&
1572 (CLASS_OF(adat->imag) == CLASS_OF(bdat->imag)) &&
1573 f_eqeq_p(self, other));
1576 return Qfalse;
1579 inline static int
1580 f_signbit(VALUE x)
1582 if (RB_FLOAT_TYPE_P(x)) {
1583 double f = RFLOAT_VALUE(x);
1584 return !isnan(f) && signbit(f);
1586 return f_negative_p(x);
1589 inline static int
1590 f_tpositive_p(VALUE x)
1592 return !f_signbit(x);
1595 static VALUE
1596 f_format(VALUE self, VALUE (*func)(VALUE))
1598 VALUE s;
1599 int impos;
1601 get_dat1(self);
1603 impos = f_tpositive_p(dat->imag);
1605 s = (*func)(dat->real);
1606 rb_str_cat2(s, !impos ? "-" : "+");
1608 rb_str_concat(s, (*func)(f_abs(dat->imag)));
1609 if (!rb_isdigit(RSTRING_PTR(s)[RSTRING_LEN(s) - 1]))
1610 rb_str_cat2(s, "*");
1611 rb_str_cat2(s, "i");
1613 return s;
1617 * call-seq:
1618 * to_s -> string
1620 * Returns a string representation of +self+:
1622 * Complex.rect(2).to_s # => "2+0i"
1623 * Complex.rect(-8, 6).to_s # => "-8+6i"
1624 * Complex.rect(0, Rational(1, 2)).to_s # => "0+1/2i"
1625 * Complex.rect(0, Float::INFINITY).to_s # => "0+Infinity*i"
1626 * Complex.rect(Float::NAN, Float::NAN).to_s # => "NaN+NaN*i"
1629 static VALUE
1630 nucomp_to_s(VALUE self)
1632 return f_format(self, rb_String);
1636 * call-seq:
1637 * inspect -> string
1639 * Returns a string representation of +self+:
1641 * Complex.rect(2).inspect # => "(2+0i)"
1642 * Complex.rect(-8, 6).inspect # => "(-8+6i)"
1643 * Complex.rect(0, Rational(1, 2)).inspect # => "(0+(1/2)*i)"
1644 * Complex.rect(0, Float::INFINITY).inspect # => "(0+Infinity*i)"
1645 * Complex.rect(Float::NAN, Float::NAN).inspect # => "(NaN+NaN*i)"
1648 static VALUE
1649 nucomp_inspect(VALUE self)
1651 VALUE s;
1653 s = rb_usascii_str_new2("(");
1654 rb_str_concat(s, f_format(self, rb_inspect));
1655 rb_str_cat2(s, ")");
1657 return s;
1660 #define FINITE_TYPE_P(v) (RB_INTEGER_TYPE_P(v) || RB_TYPE_P(v, T_RATIONAL))
1663 * call-seq:
1664 * finite? -> true or false
1666 * Returns +true+ if both <tt>self.real.finite?</tt> and <tt>self.imag.finite?</tt>
1667 * are true, +false+ otherwise:
1669 * Complex.rect(1, 1).finite? # => true
1670 * Complex.rect(Float::INFINITY, 0).finite? # => false
1672 * Related: Numeric#finite?, Float#finite?.
1674 static VALUE
1675 rb_complex_finite_p(VALUE self)
1677 get_dat1(self);
1679 return RBOOL(f_finite_p(dat->real) && f_finite_p(dat->imag));
1683 * call-seq:
1684 * infinite? -> 1 or nil
1686 * Returns +1+ if either <tt>self.real.infinite?</tt> or <tt>self.imag.infinite?</tt>
1687 * is true, +nil+ otherwise:
1689 * Complex.rect(Float::INFINITY, 0).infinite? # => 1
1690 * Complex.rect(1, 1).infinite? # => nil
1692 * Related: Numeric#infinite?, Float#infinite?.
1694 static VALUE
1695 rb_complex_infinite_p(VALUE self)
1697 get_dat1(self);
1699 if (!f_infinite_p(dat->real) && !f_infinite_p(dat->imag)) {
1700 return Qnil;
1702 return ONE;
1705 /* :nodoc: */
1706 static VALUE
1707 nucomp_dumper(VALUE self)
1709 return self;
1712 /* :nodoc: */
1713 static VALUE
1714 nucomp_loader(VALUE self, VALUE a)
1716 get_dat1(self);
1718 RCOMPLEX_SET_REAL(dat, rb_ivar_get(a, id_i_real));
1719 RCOMPLEX_SET_IMAG(dat, rb_ivar_get(a, id_i_imag));
1720 OBJ_FREEZE(self);
1722 return self;
1725 /* :nodoc: */
1726 static VALUE
1727 nucomp_marshal_dump(VALUE self)
1729 VALUE a;
1730 get_dat1(self);
1732 a = rb_assoc_new(dat->real, dat->imag);
1733 rb_copy_generic_ivar(a, self);
1734 return a;
1737 /* :nodoc: */
1738 static VALUE
1739 nucomp_marshal_load(VALUE self, VALUE a)
1741 Check_Type(a, T_ARRAY);
1742 if (RARRAY_LEN(a) != 2)
1743 rb_raise(rb_eArgError, "marshaled complex must have an array whose length is 2 but %ld", RARRAY_LEN(a));
1744 rb_ivar_set(self, id_i_real, RARRAY_AREF(a, 0));
1745 rb_ivar_set(self, id_i_imag, RARRAY_AREF(a, 1));
1746 return self;
1749 VALUE
1750 rb_complex_raw(VALUE x, VALUE y)
1752 return nucomp_s_new_internal(rb_cComplex, x, y);
1755 VALUE
1756 rb_complex_new(VALUE x, VALUE y)
1758 return nucomp_s_canonicalize_internal(rb_cComplex, x, y);
1761 VALUE
1762 rb_complex_new_polar(VALUE x, VALUE y)
1764 return f_complex_polar(rb_cComplex, x, y);
1767 VALUE
1768 rb_complex_polar(VALUE x, VALUE y)
1770 return rb_complex_new_polar(x, y);
1773 VALUE
1774 rb_Complex(VALUE x, VALUE y)
1776 VALUE a[2];
1777 a[0] = x;
1778 a[1] = y;
1779 return nucomp_s_convert(2, a, rb_cComplex);
1782 VALUE
1783 rb_dbl_complex_new(double real, double imag)
1785 return rb_complex_raw(DBL2NUM(real), DBL2NUM(imag));
1789 * call-seq:
1790 * to_i -> integer
1792 * Returns the value of <tt>self.real</tt> as an Integer, if possible:
1794 * Complex.rect(1, 0).to_i # => 1
1795 * Complex.rect(1, Rational(0, 1)).to_i # => 1
1797 * Raises RangeError if <tt>self.imag</tt> is not exactly zero
1798 * (either <tt>Integer(0)</tt> or <tt>Rational(0, _n_)</tt>).
1800 static VALUE
1801 nucomp_to_i(VALUE self)
1803 get_dat1(self);
1805 if (!k_exact_zero_p(dat->imag)) {
1806 rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Integer",
1807 self);
1809 return f_to_i(dat->real);
1813 * call-seq:
1814 * to_f -> float
1816 * Returns the value of <tt>self.real</tt> as a Float, if possible:
1818 * Complex.rect(1, 0).to_f # => 1.0
1819 * Complex.rect(1, Rational(0, 1)).to_f # => 1.0
1821 * Raises RangeError if <tt>self.imag</tt> is not exactly zero
1822 * (either <tt>Integer(0)</tt> or <tt>Rational(0, _n_)</tt>).
1824 static VALUE
1825 nucomp_to_f(VALUE self)
1827 get_dat1(self);
1829 if (!k_exact_zero_p(dat->imag)) {
1830 rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Float",
1831 self);
1833 return f_to_f(dat->real);
1837 * call-seq:
1838 * to_r -> rational
1840 * Returns the value of <tt>self.real</tt> as a Rational, if possible:
1842 * Complex.rect(1, 0).to_r # => (1/1)
1843 * Complex.rect(1, Rational(0, 1)).to_r # => (1/1)
1844 * Complex.rect(1, 0.0).to_r # => (1/1)
1846 * Raises RangeError if <tt>self.imag</tt> is not exactly zero
1847 * (either <tt>Integer(0)</tt> or <tt>Rational(0, _n_)</tt>)
1848 * and <tt>self.imag.to_r</tt> is not exactly zero.
1850 * Related: Complex#rationalize.
1852 static VALUE
1853 nucomp_to_r(VALUE self)
1855 get_dat1(self);
1857 if (RB_FLOAT_TYPE_P(dat->imag) && FLOAT_ZERO_P(dat->imag)) {
1858 /* Do nothing here */
1860 else if (!k_exact_zero_p(dat->imag)) {
1861 VALUE imag = rb_check_convert_type_with_id(dat->imag, T_RATIONAL, "Rational", idTo_r);
1862 if (NIL_P(imag) || !k_exact_zero_p(imag)) {
1863 rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Rational",
1864 self);
1867 return f_to_r(dat->real);
1871 * call-seq:
1872 * rationalize(epsilon = nil) -> rational
1874 * Returns a Rational object whose value is exactly or approximately
1875 * equivalent to that of <tt>self.real</tt>.
1877 * With no argument +epsilon+ given, returns a \Rational object
1878 * whose value is exactly equal to that of <tt>self.real.rationalize</tt>:
1880 * Complex.rect(1, 0).rationalize # => (1/1)
1881 * Complex.rect(1, Rational(0, 1)).rationalize # => (1/1)
1882 * Complex.rect(3.14159, 0).rationalize # => (314159/100000)
1884 * With argument +epsilon+ given, returns a \Rational object
1885 * whose value is exactly or approximately equal to that of <tt>self.real</tt>
1886 * to the given precision:
1888 * Complex.rect(3.14159, 0).rationalize(0.1) # => (16/5)
1889 * Complex.rect(3.14159, 0).rationalize(0.01) # => (22/7)
1890 * Complex.rect(3.14159, 0).rationalize(0.001) # => (201/64)
1891 * Complex.rect(3.14159, 0).rationalize(0.0001) # => (333/106)
1892 * Complex.rect(3.14159, 0).rationalize(0.00001) # => (355/113)
1893 * Complex.rect(3.14159, 0).rationalize(0.000001) # => (7433/2366)
1894 * Complex.rect(3.14159, 0).rationalize(0.0000001) # => (9208/2931)
1895 * Complex.rect(3.14159, 0).rationalize(0.00000001) # => (47460/15107)
1896 * Complex.rect(3.14159, 0).rationalize(0.000000001) # => (76149/24239)
1897 * Complex.rect(3.14159, 0).rationalize(0.0000000001) # => (314159/100000)
1898 * Complex.rect(3.14159, 0).rationalize(0.0) # => (3537115888337719/1125899906842624)
1900 * Related: Complex#to_r.
1902 static VALUE
1903 nucomp_rationalize(int argc, VALUE *argv, VALUE self)
1905 get_dat1(self);
1907 rb_check_arity(argc, 0, 1);
1909 if (!k_exact_zero_p(dat->imag)) {
1910 rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Rational",
1911 self);
1913 return rb_funcallv(dat->real, id_rationalize, argc, argv);
1917 * call-seq:
1918 * to_c -> self
1920 * Returns +self+.
1922 static VALUE
1923 nucomp_to_c(VALUE self)
1925 return self;
1929 * call-seq:
1930 * to_c -> (0+0i)
1932 * Returns zero as a Complex:
1934 * nil.to_c # => (0+0i)
1937 static VALUE
1938 nilclass_to_c(VALUE self)
1940 return rb_complex_new1(INT2FIX(0));
1944 * call-seq:
1945 * to_c -> complex
1947 * Returns +self+ as a Complex object.
1949 static VALUE
1950 numeric_to_c(VALUE self)
1952 return rb_complex_new1(self);
1955 inline static int
1956 issign(int c)
1958 return (c == '-' || c == '+');
1961 static int
1962 read_sign(const char **s,
1963 char **b)
1965 int sign = '?';
1967 if (issign(**s)) {
1968 sign = **b = **s;
1969 (*s)++;
1970 (*b)++;
1972 return sign;
1975 inline static int
1976 isdecimal(int c)
1978 return isdigit((unsigned char)c);
1981 static int
1982 read_digits(const char **s, int strict,
1983 char **b)
1985 int us = 1;
1987 if (!isdecimal(**s))
1988 return 0;
1990 while (isdecimal(**s) || **s == '_') {
1991 if (**s == '_') {
1992 if (us) {
1993 if (strict) return 0;
1994 break;
1996 us = 1;
1998 else {
1999 **b = **s;
2000 (*b)++;
2001 us = 0;
2003 (*s)++;
2005 if (us)
2006 do {
2007 (*s)--;
2008 } while (**s == '_');
2009 return 1;
2012 inline static int
2013 islettere(int c)
2015 return (c == 'e' || c == 'E');
2018 static int
2019 read_num(const char **s, int strict,
2020 char **b)
2022 if (**s != '.') {
2023 if (!read_digits(s, strict, b))
2024 return 0;
2027 if (**s == '.') {
2028 **b = **s;
2029 (*s)++;
2030 (*b)++;
2031 if (!read_digits(s, strict, b)) {
2032 (*b)--;
2033 return 0;
2037 if (islettere(**s)) {
2038 **b = **s;
2039 (*s)++;
2040 (*b)++;
2041 read_sign(s, b);
2042 if (!read_digits(s, strict, b)) {
2043 (*b)--;
2044 return 0;
2047 return 1;
2050 inline static int
2051 read_den(const char **s, int strict,
2052 char **b)
2054 if (!read_digits(s, strict, b))
2055 return 0;
2056 return 1;
2059 static int
2060 read_rat_nos(const char **s, int strict,
2061 char **b)
2063 if (!read_num(s, strict, b))
2064 return 0;
2065 if (**s == '/') {
2066 **b = **s;
2067 (*s)++;
2068 (*b)++;
2069 if (!read_den(s, strict, b)) {
2070 (*b)--;
2071 return 0;
2074 return 1;
2077 static int
2078 read_rat(const char **s, int strict,
2079 char **b)
2081 read_sign(s, b);
2082 if (!read_rat_nos(s, strict, b))
2083 return 0;
2084 return 1;
2087 inline static int
2088 isimagunit(int c)
2090 return (c == 'i' || c == 'I' ||
2091 c == 'j' || c == 'J');
2094 static VALUE
2095 str2num(char *s)
2097 if (strchr(s, '/'))
2098 return rb_cstr_to_rat(s, 0);
2099 if (strpbrk(s, ".eE"))
2100 return DBL2NUM(rb_cstr_to_dbl(s, 0));
2101 return rb_cstr_to_inum(s, 10, 0);
2104 static int
2105 read_comp(const char **s, int strict,
2106 VALUE *ret, char **b)
2108 char *bb;
2109 int sign;
2110 VALUE num, num2;
2112 bb = *b;
2114 sign = read_sign(s, b);
2116 if (isimagunit(**s)) {
2117 (*s)++;
2118 num = INT2FIX((sign == '-') ? -1 : + 1);
2119 *ret = rb_complex_new2(ZERO, num);
2120 return 1; /* e.g. "i" */
2123 if (!read_rat_nos(s, strict, b)) {
2124 **b = '\0';
2125 num = str2num(bb);
2126 *ret = rb_complex_new2(num, ZERO);
2127 return 0; /* e.g. "-" */
2129 **b = '\0';
2130 num = str2num(bb);
2132 if (isimagunit(**s)) {
2133 (*s)++;
2134 *ret = rb_complex_new2(ZERO, num);
2135 return 1; /* e.g. "3i" */
2138 if (**s == '@') {
2139 int st;
2141 (*s)++;
2142 bb = *b;
2143 st = read_rat(s, strict, b);
2144 **b = '\0';
2145 if (strlen(bb) < 1 ||
2146 !isdecimal(*(bb + strlen(bb) - 1))) {
2147 *ret = rb_complex_new2(num, ZERO);
2148 return 0; /* e.g. "1@-" */
2150 num2 = str2num(bb);
2151 *ret = rb_complex_new_polar(num, num2);
2152 if (!st)
2153 return 0; /* e.g. "1@2." */
2154 else
2155 return 1; /* e.g. "1@2" */
2158 if (issign(**s)) {
2159 bb = *b;
2160 sign = read_sign(s, b);
2161 if (isimagunit(**s))
2162 num2 = INT2FIX((sign == '-') ? -1 : + 1);
2163 else {
2164 if (!read_rat_nos(s, strict, b)) {
2165 *ret = rb_complex_new2(num, ZERO);
2166 return 0; /* e.g. "1+xi" */
2168 **b = '\0';
2169 num2 = str2num(bb);
2171 if (!isimagunit(**s)) {
2172 *ret = rb_complex_new2(num, ZERO);
2173 return 0; /* e.g. "1+3x" */
2175 (*s)++;
2176 *ret = rb_complex_new2(num, num2);
2177 return 1; /* e.g. "1+2i" */
2179 /* !(@, - or +) */
2181 *ret = rb_complex_new2(num, ZERO);
2182 return 1; /* e.g. "3" */
2186 inline static void
2187 skip_ws(const char **s)
2189 while (isspace((unsigned char)**s))
2190 (*s)++;
2193 static int
2194 parse_comp(const char *s, int strict, VALUE *num)
2196 char *buf, *b;
2197 VALUE tmp;
2198 int ret = 1;
2200 buf = ALLOCV_N(char, tmp, strlen(s) + 1);
2201 b = buf;
2203 skip_ws(&s);
2204 if (!read_comp(&s, strict, num, &b)) {
2205 ret = 0;
2207 else {
2208 skip_ws(&s);
2210 if (strict)
2211 if (*s != '\0')
2212 ret = 0;
2214 ALLOCV_END(tmp);
2216 return ret;
2219 static VALUE
2220 string_to_c_strict(VALUE self, int raise)
2222 char *s;
2223 VALUE num;
2225 rb_must_asciicompat(self);
2227 if (raise) {
2228 s = StringValueCStr(self);
2230 else if (!(s = rb_str_to_cstr(self))) {
2231 return Qnil;
2234 if (!parse_comp(s, TRUE, &num)) {
2235 if (!raise) return Qnil;
2236 rb_raise(rb_eArgError, "invalid value for convert(): %+"PRIsVALUE,
2237 self);
2240 return num;
2244 * call-seq:
2245 * to_c -> complex
2247 * Returns +self+ interpreted as a Complex object;
2248 * leading whitespace and trailing garbage are ignored:
2250 * '9'.to_c # => (9+0i)
2251 * '2.5'.to_c # => (2.5+0i)
2252 * '2.5/1'.to_c # => ((5/2)+0i)
2253 * '-3/2'.to_c # => ((-3/2)+0i)
2254 * '-i'.to_c # => (0-1i)
2255 * '45i'.to_c # => (0+45i)
2256 * '3-4i'.to_c # => (3-4i)
2257 * '-4e2-4e-2i'.to_c # => (-400.0-0.04i)
2258 * '-0.0-0.0i'.to_c # => (-0.0-0.0i)
2259 * '1/2+3/4i'.to_c # => ((1/2)+(3/4)*i)
2260 * '1.0@0'.to_c # => (1+0.0i)
2261 * "1.0@#{Math::PI/2}".to_c # => (0.0+1i)
2262 * "1.0@#{Math::PI}".to_c # => (-1+0.0i)
2264 * Returns \Complex zero if the string cannot be converted:
2266 * 'ruby'.to_c # => (0+0i)
2268 * See Kernel#Complex.
2270 static VALUE
2271 string_to_c(VALUE self)
2273 VALUE num;
2275 rb_must_asciicompat(self);
2277 (void)parse_comp(rb_str_fill_terminator(self, 1), FALSE, &num);
2279 return num;
2282 static VALUE
2283 to_complex(VALUE val)
2285 return rb_convert_type(val, T_COMPLEX, "Complex", "to_c");
2288 static VALUE
2289 nucomp_convert(VALUE klass, VALUE a1, VALUE a2, int raise)
2291 if (NIL_P(a1) || NIL_P(a2)) {
2292 if (!raise) return Qnil;
2293 rb_raise(rb_eTypeError, "can't convert nil into Complex");
2296 if (RB_TYPE_P(a1, T_STRING)) {
2297 a1 = string_to_c_strict(a1, raise);
2298 if (NIL_P(a1)) return Qnil;
2301 if (RB_TYPE_P(a2, T_STRING)) {
2302 a2 = string_to_c_strict(a2, raise);
2303 if (NIL_P(a2)) return Qnil;
2306 if (RB_TYPE_P(a1, T_COMPLEX)) {
2308 get_dat1(a1);
2310 if (k_exact_zero_p(dat->imag))
2311 a1 = dat->real;
2315 if (RB_TYPE_P(a2, T_COMPLEX)) {
2317 get_dat1(a2);
2319 if (k_exact_zero_p(dat->imag))
2320 a2 = dat->real;
2324 if (RB_TYPE_P(a1, T_COMPLEX)) {
2325 if (UNDEF_P(a2) || (k_exact_zero_p(a2)))
2326 return a1;
2329 if (UNDEF_P(a2)) {
2330 if (k_numeric_p(a1) && !f_real_p(a1))
2331 return a1;
2332 /* should raise exception for consistency */
2333 if (!k_numeric_p(a1)) {
2334 if (!raise) {
2335 a1 = rb_protect(to_complex, a1, NULL);
2336 rb_set_errinfo(Qnil);
2337 return a1;
2339 return to_complex(a1);
2342 else {
2343 if ((k_numeric_p(a1) && k_numeric_p(a2)) &&
2344 (!f_real_p(a1) || !f_real_p(a2)))
2345 return f_add(a1,
2346 f_mul(a2,
2347 f_complex_new_bang2(rb_cComplex, ZERO, ONE)));
2351 int argc;
2352 VALUE argv2[2];
2353 argv2[0] = a1;
2354 if (UNDEF_P(a2)) {
2355 argv2[1] = Qnil;
2356 argc = 1;
2358 else {
2359 if (!raise && !RB_INTEGER_TYPE_P(a2) && !RB_FLOAT_TYPE_P(a2) && !RB_TYPE_P(a2, T_RATIONAL))
2360 return Qnil;
2361 argv2[1] = a2;
2362 argc = 2;
2364 return nucomp_s_new(argc, argv2, klass);
2368 static VALUE
2369 nucomp_s_convert(int argc, VALUE *argv, VALUE klass)
2371 VALUE a1, a2;
2373 if (rb_scan_args(argc, argv, "11", &a1, &a2) == 1) {
2374 a2 = Qundef;
2377 return nucomp_convert(klass, a1, a2, TRUE);
2381 * call-seq:
2382 * abs2 -> real
2384 * Returns the square of +self+.
2386 static VALUE
2387 numeric_abs2(VALUE self)
2389 return f_mul(self, self);
2393 * call-seq:
2394 * arg -> 0 or Math::PI
2396 * Returns zero if +self+ is positive, Math::PI otherwise.
2398 static VALUE
2399 numeric_arg(VALUE self)
2401 if (f_positive_p(self))
2402 return INT2FIX(0);
2403 return DBL2NUM(M_PI);
2407 * call-seq:
2408 * rect -> array
2410 * Returns array <tt>[self, 0]</tt>.
2412 static VALUE
2413 numeric_rect(VALUE self)
2415 return rb_assoc_new(self, INT2FIX(0));
2419 * call-seq:
2420 * polar -> array
2422 * Returns array <tt>[self.abs, self.arg]</tt>.
2424 static VALUE
2425 numeric_polar(VALUE self)
2427 VALUE abs, arg;
2429 if (RB_INTEGER_TYPE_P(self)) {
2430 abs = rb_int_abs(self);
2431 arg = numeric_arg(self);
2433 else if (RB_FLOAT_TYPE_P(self)) {
2434 abs = rb_float_abs(self);
2435 arg = float_arg(self);
2437 else if (RB_TYPE_P(self, T_RATIONAL)) {
2438 abs = rb_rational_abs(self);
2439 arg = numeric_arg(self);
2441 else {
2442 abs = f_abs(self);
2443 arg = f_arg(self);
2445 return rb_assoc_new(abs, arg);
2449 * call-seq:
2450 * arg -> 0 or Math::PI
2452 * Returns 0 if +self+ is positive, Math::PI otherwise.
2454 static VALUE
2455 float_arg(VALUE self)
2457 if (isnan(RFLOAT_VALUE(self)))
2458 return self;
2459 if (f_tpositive_p(self))
2460 return INT2FIX(0);
2461 return rb_const_get(rb_mMath, id_PI);
2465 * A \Complex object houses a pair of values,
2466 * given when the object is created as either <i>rectangular coordinates</i>
2467 * or <i>polar coordinates</i>.
2469 * == Rectangular Coordinates
2471 * The rectangular coordinates of a complex number
2472 * are called the _real_ and _imaginary_ parts;
2473 * see {Complex number definition}[https://en.wikipedia.org/wiki/Complex_number#Definition_and_basic_operations].
2475 * You can create a \Complex object from rectangular coordinates with:
2477 * - A {complex literal}[rdoc-ref:doc/syntax/literals.rdoc@Complex+Literals].
2478 * - \Method Complex.rect.
2479 * - \Method Kernel#Complex, either with numeric arguments or with certain string arguments.
2480 * - \Method String#to_c, for certain strings.
2482 * Note that each of the stored parts may be a an instance one of the classes
2483 * Complex, Float, Integer, or Rational;
2484 * they may be retrieved:
2486 * - Separately, with methods Complex#real and Complex#imaginary.
2487 * - Together, with method Complex#rect.
2489 * The corresponding (computed) polar values may be retrieved:
2491 * - Separately, with methods Complex#abs and Complex#arg.
2492 * - Together, with method Complex#polar.
2494 * == Polar Coordinates
2496 * The polar coordinates of a complex number
2497 * are called the _absolute_ and _argument_ parts;
2498 * see {Complex polar plane}[https://en.wikipedia.org/wiki/Complex_number#Polar_form].
2500 * In this class, the argument part
2501 * in expressed {radians}[https://en.wikipedia.org/wiki/Radian]
2502 * (not {degrees}[https://en.wikipedia.org/wiki/Degree_(angle)]).
2504 * You can create a \Complex object from polar coordinates with:
2506 * - \Method Complex.polar.
2507 * - \Method Kernel#Complex, with certain string arguments.
2508 * - \Method String#to_c, for certain strings.
2510 * Note that each of the stored parts may be a an instance one of the classes
2511 * Complex, Float, Integer, or Rational;
2512 * they may be retrieved:
2514 * - Separately, with methods Complex#abs and Complex#arg.
2515 * - Together, with method Complex#polar.
2517 * The corresponding (computed) rectangular values may be retrieved:
2519 * - Separately, with methods Complex#real and Complex#imag.
2520 * - Together, with method Complex#rect.
2522 * == What's Here
2524 * First, what's elsewhere:
2526 * - \Class \Complex inherits (directly or indirectly)
2527 * from classes {Numeric}[rdoc-ref:Numeric@What-27s+Here]
2528 * and {Object}[rdoc-ref:Object@What-27s+Here].
2529 * - Includes (indirectly) module {Comparable}[rdoc-ref:Comparable@What-27s+Here].
2531 * Here, class \Complex has methods for:
2533 * === Creating \Complex Objects
2535 * - ::polar: Returns a new \Complex object based on given polar coordinates.
2536 * - ::rect (and its alias ::rectangular):
2537 * Returns a new \Complex object based on given rectangular coordinates.
2539 * === Querying
2541 * - #abs (and its alias #magnitude): Returns the absolute value for +self+.
2542 * - #arg (and its aliases #angle and #phase):
2543 * Returns the argument (angle) for +self+ in radians.
2544 * - #denominator: Returns the denominator of +self+.
2545 * - #finite?: Returns whether both +self.real+ and +self.image+ are finite.
2546 * - #hash: Returns the integer hash value for +self+.
2547 * - #imag (and its alias #imaginary): Returns the imaginary value for +self+.
2548 * - #infinite?: Returns whether +self.real+ or +self.image+ is infinite.
2549 * - #numerator: Returns the numerator of +self+.
2550 * - #polar: Returns the array <tt>[self.abs, self.arg]</tt>.
2551 * - #inspect: Returns a string representation of +self+.
2552 * - #real: Returns the real value for +self+.
2553 * - #real?: Returns +false+; for compatibility with Numeric#real?.
2554 * - #rect (and its alias #rectangular):
2555 * Returns the array <tt>[self.real, self.imag]</tt>.
2557 * === Comparing
2559 * - #<=>: Returns whether +self+ is less than, equal to, or greater than the given argument.
2560 * - #==: Returns whether +self+ is equal to the given argument.
2562 * === Converting
2564 * - #rationalize: Returns a Rational object whose value is exactly
2565 * or approximately equivalent to that of <tt>self.real</tt>.
2566 * - #to_c: Returns +self+.
2567 * - #to_d: Returns the value as a BigDecimal object.
2568 * - #to_f: Returns the value of <tt>self.real</tt> as a Float, if possible.
2569 * - #to_i: Returns the value of <tt>self.real</tt> as an Integer, if possible.
2570 * - #to_r: Returns the value of <tt>self.real</tt> as a Rational, if possible.
2571 * - #to_s: Returns a string representation of +self+.
2573 * === Performing Complex Arithmetic
2575 * - #*: Returns the product of +self+ and the given numeric.
2576 * - #**: Returns +self+ raised to power of the given numeric.
2577 * - #+: Returns the sum of +self+ and the given numeric.
2578 * - #-: Returns the difference of +self+ and the given numeric.
2579 * - #-@: Returns the negation of +self+.
2580 * - #/: Returns the quotient of +self+ and the given numeric.
2581 * - #abs2: Returns square of the absolute value (magnitude) for +self+.
2582 * - #conj (and its alias #conjugate): Returns the conjugate of +self+.
2583 * - #fdiv: Returns <tt>Complex.rect(self.real/numeric, self.imag/numeric)</tt>.
2585 * === Working with JSON
2587 * - ::json_create: Returns a new \Complex object,
2588 * deserialized from the given serialized hash.
2589 * - #as_json: Returns a serialized hash constructed from +self+.
2590 * - #to_json: Returns a JSON string representing +self+.
2592 * These methods are provided by the {JSON gem}[https://github.com/flori/json]. To make these methods available:
2594 * require 'json/add/complex'
2597 void
2598 Init_Complex(void)
2600 VALUE compat;
2601 id_abs = rb_intern_const("abs");
2602 id_arg = rb_intern_const("arg");
2603 id_denominator = rb_intern_const("denominator");
2604 id_numerator = rb_intern_const("numerator");
2605 id_real_p = rb_intern_const("real?");
2606 id_i_real = rb_intern_const("@real");
2607 id_i_imag = rb_intern_const("@image"); /* @image, not @imag */
2608 id_finite_p = rb_intern_const("finite?");
2609 id_infinite_p = rb_intern_const("infinite?");
2610 id_rationalize = rb_intern_const("rationalize");
2611 id_PI = rb_intern_const("PI");
2613 rb_cComplex = rb_define_class("Complex", rb_cNumeric);
2615 rb_define_alloc_func(rb_cComplex, nucomp_s_alloc);
2616 rb_undef_method(CLASS_OF(rb_cComplex), "allocate");
2618 rb_undef_method(CLASS_OF(rb_cComplex), "new");
2620 rb_define_singleton_method(rb_cComplex, "rectangular", nucomp_s_new, -1);
2621 rb_define_singleton_method(rb_cComplex, "rect", nucomp_s_new, -1);
2622 rb_define_singleton_method(rb_cComplex, "polar", nucomp_s_polar, -1);
2624 rb_define_global_function("Complex", nucomp_f_complex, -1);
2626 rb_undef_methods_from(rb_cComplex, RCLASS_ORIGIN(rb_mComparable));
2627 rb_undef_method(rb_cComplex, "%");
2628 rb_undef_method(rb_cComplex, "div");
2629 rb_undef_method(rb_cComplex, "divmod");
2630 rb_undef_method(rb_cComplex, "floor");
2631 rb_undef_method(rb_cComplex, "ceil");
2632 rb_undef_method(rb_cComplex, "modulo");
2633 rb_undef_method(rb_cComplex, "remainder");
2634 rb_undef_method(rb_cComplex, "round");
2635 rb_undef_method(rb_cComplex, "step");
2636 rb_undef_method(rb_cComplex, "truncate");
2637 rb_undef_method(rb_cComplex, "i");
2639 rb_define_method(rb_cComplex, "real", rb_complex_real, 0);
2640 rb_define_method(rb_cComplex, "imaginary", rb_complex_imag, 0);
2641 rb_define_method(rb_cComplex, "imag", rb_complex_imag, 0);
2643 rb_define_method(rb_cComplex, "-@", rb_complex_uminus, 0);
2644 rb_define_method(rb_cComplex, "+", rb_complex_plus, 1);
2645 rb_define_method(rb_cComplex, "-", rb_complex_minus, 1);
2646 rb_define_method(rb_cComplex, "*", rb_complex_mul, 1);
2647 rb_define_method(rb_cComplex, "/", rb_complex_div, 1);
2648 rb_define_method(rb_cComplex, "quo", nucomp_quo, 1);
2649 rb_define_method(rb_cComplex, "fdiv", nucomp_fdiv, 1);
2650 rb_define_method(rb_cComplex, "**", rb_complex_pow, 1);
2652 rb_define_method(rb_cComplex, "==", nucomp_eqeq_p, 1);
2653 rb_define_method(rb_cComplex, "<=>", nucomp_cmp, 1);
2654 rb_define_method(rb_cComplex, "coerce", nucomp_coerce, 1);
2656 rb_define_method(rb_cComplex, "abs", rb_complex_abs, 0);
2657 rb_define_method(rb_cComplex, "magnitude", rb_complex_abs, 0);
2658 rb_define_method(rb_cComplex, "abs2", nucomp_abs2, 0);
2659 rb_define_method(rb_cComplex, "arg", rb_complex_arg, 0);
2660 rb_define_method(rb_cComplex, "angle", rb_complex_arg, 0);
2661 rb_define_method(rb_cComplex, "phase", rb_complex_arg, 0);
2662 rb_define_method(rb_cComplex, "rectangular", nucomp_rect, 0);
2663 rb_define_method(rb_cComplex, "rect", nucomp_rect, 0);
2664 rb_define_method(rb_cComplex, "polar", nucomp_polar, 0);
2665 rb_define_method(rb_cComplex, "conjugate", rb_complex_conjugate, 0);
2666 rb_define_method(rb_cComplex, "conj", rb_complex_conjugate, 0);
2668 rb_define_method(rb_cComplex, "real?", nucomp_real_p_m, 0);
2670 rb_define_method(rb_cComplex, "numerator", nucomp_numerator, 0);
2671 rb_define_method(rb_cComplex, "denominator", nucomp_denominator, 0);
2673 rb_define_method(rb_cComplex, "hash", nucomp_hash, 0);
2674 rb_define_method(rb_cComplex, "eql?", nucomp_eql_p, 1);
2676 rb_define_method(rb_cComplex, "to_s", nucomp_to_s, 0);
2677 rb_define_method(rb_cComplex, "inspect", nucomp_inspect, 0);
2679 rb_undef_method(rb_cComplex, "positive?");
2680 rb_undef_method(rb_cComplex, "negative?");
2682 rb_define_method(rb_cComplex, "finite?", rb_complex_finite_p, 0);
2683 rb_define_method(rb_cComplex, "infinite?", rb_complex_infinite_p, 0);
2685 rb_define_private_method(rb_cComplex, "marshal_dump", nucomp_marshal_dump, 0);
2686 /* :nodoc: */
2687 compat = rb_define_class_under(rb_cComplex, "compatible", rb_cObject);
2688 rb_define_private_method(compat, "marshal_load", nucomp_marshal_load, 1);
2689 rb_marshal_define_compat(rb_cComplex, compat, nucomp_dumper, nucomp_loader);
2691 rb_define_method(rb_cComplex, "to_i", nucomp_to_i, 0);
2692 rb_define_method(rb_cComplex, "to_f", nucomp_to_f, 0);
2693 rb_define_method(rb_cComplex, "to_r", nucomp_to_r, 0);
2694 rb_define_method(rb_cComplex, "rationalize", nucomp_rationalize, -1);
2695 rb_define_method(rb_cComplex, "to_c", nucomp_to_c, 0);
2696 rb_define_method(rb_cNilClass, "to_c", nilclass_to_c, 0);
2697 rb_define_method(rb_cNumeric, "to_c", numeric_to_c, 0);
2699 rb_define_method(rb_cString, "to_c", string_to_c, 0);
2701 rb_define_private_method(CLASS_OF(rb_cComplex), "convert", nucomp_s_convert, -1);
2703 rb_define_method(rb_cNumeric, "abs2", numeric_abs2, 0);
2704 rb_define_method(rb_cNumeric, "arg", numeric_arg, 0);
2705 rb_define_method(rb_cNumeric, "angle", numeric_arg, 0);
2706 rb_define_method(rb_cNumeric, "phase", numeric_arg, 0);
2707 rb_define_method(rb_cNumeric, "rectangular", numeric_rect, 0);
2708 rb_define_method(rb_cNumeric, "rect", numeric_rect, 0);
2709 rb_define_method(rb_cNumeric, "polar", numeric_polar, 0);
2711 rb_define_method(rb_cFloat, "arg", float_arg, 0);
2712 rb_define_method(rb_cFloat, "angle", float_arg, 0);
2713 rb_define_method(rb_cFloat, "phase", float_arg, 0);
2716 * Equivalent
2717 * to <tt>Complex.rect(0, 1)</tt>:
2719 * Complex::I # => (0+1i)
2722 rb_define_const(rb_cComplex, "I",
2723 f_complex_new_bang2(rb_cComplex, ZERO, ONE));
2725 #if !USE_FLONUM
2726 rb_vm_register_global_object(RFLOAT_0 = DBL2NUM(0.0));
2727 #endif
2729 rb_provide("complex.so"); /* for backward compatibility */