diff options
| author | Yukihiro "Matz" Matsumoto <[email protected]> | 2021-03-24 09:53:39 +0900 |
|---|---|---|
| committer | Yukihiro "Matz" Matsumoto <[email protected]> | 2021-03-24 09:53:39 +0900 |
| commit | 5573707d7f0ea82fc6fd6335bd23dd9ab6ccbca7 (patch) | |
| tree | d16419f669cec75438b60957939fd5c497428bee /mrbgems/mruby-complex | |
| parent | dc5d74dda8432bcc1e9dfce73c722f6259aeb08a (diff) | |
| download | mruby-5573707d7f0ea82fc6fd6335bd23dd9ab6ccbca7.tar.gz mruby-5573707d7f0ea82fc6fd6335bd23dd9ab6ccbca7.zip | |
complex.c: implement `Complex#*` in C.
Diffstat (limited to 'mrbgems/mruby-complex')
| -rw-r--r-- | mrbgems/mruby-complex/mrblib/complex.rb | 8 | ||||
| -rw-r--r-- | mrbgems/mruby-complex/src/complex.c | 23 |
2 files changed, 23 insertions, 8 deletions
diff --git a/mrbgems/mruby-complex/mrblib/complex.rb b/mrbgems/mruby-complex/mrblib/complex.rb index 6372d36f6..f07cb4ba5 100644 --- a/mrbgems/mruby-complex/mrblib/complex.rb +++ b/mrbgems/mruby-complex/mrblib/complex.rb @@ -35,14 +35,6 @@ class Complex < Numeric end end - def *(rhs) - if rhs.is_a? Complex - Complex(real * rhs.real - imaginary * rhs.imaginary, real * rhs.imaginary + rhs.real * imaginary) - elsif rhs.is_a? Numeric - Complex(real * rhs, imaginary * rhs) - end - end - def /(rhs) if rhs.is_a? Complex __div__(rhs) diff --git a/mrbgems/mruby-complex/src/complex.c b/mrbgems/mruby-complex/src/complex.c index 67ab9c33d..c0db0f957 100644 --- a/mrbgems/mruby-complex/src/complex.c +++ b/mrbgems/mruby-complex/src/complex.c @@ -171,6 +171,28 @@ complex_eq(mrb_state *mrb, mrb_value x) return mrb_bool_value(mrb_complex_eq(mrb, x, y)); } +static mrb_value +complex_mul(mrb_state *mrb, mrb_value x) +{ + mrb_value y = mrb_get_arg1(mrb); + struct mrb_complex *p1 = complex_ptr(mrb, x); + + switch (mrb_type(y)) { + case MRB_TT_COMPLEX: + { + struct mrb_complex *p2 = complex_ptr(mrb, y); + return mrb_complex_new(mrb, p1->real*p2->real - p1->imaginary*p2->imaginary, + p1->real*p2->imaginary + p2->real*p1->imaginary); + } + + default: + { + mrb_float z = mrb_to_flo(mrb, y); + return mrb_complex_new(mrb, p1->real*z, p1->imaginary*z); + } + } +} + /* Arithmetic on (significand, exponent) pairs avoids premature overflow in complex division */ struct float_pair { @@ -322,6 +344,7 @@ void mrb_mruby_complex_gem_init(mrb_state *mrb) mrb_define_method(mrb, comp, "to_f", complex_to_f, MRB_ARGS_NONE()); mrb_define_method(mrb, comp, "to_i", complex_to_i, MRB_ARGS_NONE()); mrb_define_method(mrb, comp, "to_c", complex_to_c, MRB_ARGS_NONE()); + mrb_define_method(mrb, comp, "*", complex_mul, MRB_ARGS_REQ(1)); mrb_define_method(mrb, comp, "__div__", complex_div, MRB_ARGS_REQ(1)); mrb_define_method(mrb, comp, "==", complex_eq, MRB_ARGS_REQ(1)); #ifndef MRB_USE_RATIONAL |
