File: complex.rb

package info (click to toggle)
jblas 1.2.0-4
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 46,164 kB
  • sloc: java: 11,050; ansic: 4,152; ruby: 2,290; xml: 289; makefile: 132; sh: 22
file content (47 lines) | stat: -rw-r--r-- 1,069 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# This file demonstrates how to access a java file contained in a
# jar file, how to extend the java object and make a numeric
# class interact seamlessly with normal ruby numeric objects

# load the jar file
require '../jBLAS.jar'

# We provide a short-cut for the class com.fhg.core.DoubleComplex
DoubleComplex = Java::edu.ida.core.DoubleComplex

# we extend the class
class DoubleComplex
  # add operators
  def +(o); add(promote(o)); end
  def -(o); sub(promote(o)); end
  def *(o); mul(promote(o)); end
  def /(o); div(promote(o)); end

  # extend the range of the operators to also deal with
  # non-complex numeric arguments
  def promote(o)
    if Numeric === o
      DoubleComplex.new(o, 0)
    else
      o
    end
  end

  # make sure that it also works when the left hand side operator
  # is not a double
  def coerce(o)
    unless DoubleComplex === o
      [self, o]
    end
  end

  # to make sure that we look pretty in irb
  def inspect
    toString
  end
end

# imaginary number
I = DoubleComplex.new(0, 1)

# and voila, it works!
puts (1 + 3*I)/ 2*I