ruby picture

RCR 195: built-in complex math

Submitted by discordantus (Sat Jan 17 05:01:44 UTC 2004)

Abstract

Speeding up operations using complex numbers by implementing the Complex class as a built-in.

Problem

Currently, math using complex numbers is very slow, because the Complex class is implemented in pure Ruby. This makes it difficult to feel good about using Ruby for anything requiring large amounts of complex number crunching.

Proposal

Complex numbers could be implemented in C as a Ruby built-in class.

Analysis

I did some tests, comparing the performance of Ruby's complex mathematics with that of Python's. Here are the scripts I used:

Ruby:

require 'complex'
(1..15).each do |x|
  (1..15).each do |y|
    (1..15).each do |u|
      (1..15).each do |v|
        a = Complex.new(x,y)
        b = Complex.new(u,v)
        [a*b,a/b,a-b,a+b]
      end
    end
  end
end

Python:

for x in range(1,16):
  for y in range(1,16):
    for u in range(1,16):
      for v in range(1,16):
        a = x+y*1j
        b = u+v*1j
        [a*b,a/b,a-b,a+b]

The Ruby version took 39.04s of processor time to complete the script. The Python version took 2.24s of processor time.
I tried it again, but with the mathematical operations excised and just the complex number creation and assignment intact. This was just to see how much of the speed difference was tied to the fact that I was creating over 50000 complex numbers. With those modifications, the Ruby version took 4.38s while Python took 1.22s.

These tests suggest that if a built-in version of Ruby's complex math is even half as fast as Python's, it would give nearly a 90% reduction in computation time

Implementation

The implementation would be in C, presumably including all the features of the current Complex class.
ruby picture
Comments Current voting

Shin'ichiro Hara is working on C implementation of Complex, which I think, will be merged in the future version. This proposal will be accepted. The C version of Complex may or may not be built in, depending on the status of RCR#194.

-matz.


I believe Complex should have a C API. It is likely a programmer will be using C for numerical work. This implies Complex must be built in, I think, because symbols loaded from a shared library are not available transitively. That is, an extension cannot, in general, use the C functions of Complex if it is implemented as an extension. One could use rb_funcall everywhere, but this sort of defeats the original purpose of implementing Complex in C. --Jeff Mitchell


Strongly opposed 0
Opposed 0
Neutral 1
In favor 8
Strongly advocate 8
ruby picture
If you have registered at RCRchive, you may now sign in below. If you have not registered, you may sign up for a username and password. Registering enables you to submit new RCRs, and vote and leave comments on existing RCRs.
Your username:
Your password:

ruby picture

Powered by .