[Matrix-SIG] NumericFix.py

Pearu Peterson pearu@egoist.ioc.ee
Mon, 16 Nov 1998 09:17:31 +0200 (EET)


Hi!

The problem is that in order to get sqrt(-1) one has
to write sqrt(-1+0j) which, I think, is quite weird.
The same holds for arcsin(a),arccos(a) if |a|>1.
So, I propose the following fixes in the Numeric module
that is realized in the file 'NumericFix.py' (see below).

With best regards,
	Pearu

Pearu Peterson <pearu@ioc.ee>, MSc, Researcer
Department of Mechanics and Applied Mathematics          http://koer.ioc.ee/~pearu/
Institute of Cybernetics at Tallinn Technical University Phone: (+3722) 527907
Akadeemia rd. 21, 12618 Tallinn ESTONIA                  Fax:   (+372) 6397039
 
--------------- NumericFix.py -----------------
#!/usr/bin/env python
"""
In order to use the following statements (that in the Numeric module
give ValueError):
  Numeric.sqrt(-1)
  Numeric.arcsin(3)
  Numeric.arccos(3)
use `from NumericFix import Numeric` instead of `import Numeric`.
Use `from NumericFix import *` instead of `from Numeric import *`.

In addition, the functions Numeric.ceil, Numeric.floor, and Numeric.fabs
will work with complex arguments as well. For example,
Numeric.ceil(2.1-5.3j) gives (3-5j).

PS: These fixes should really be done in Numeric module.

November 16, 1998
Pearu Peterson, <pearu@ioc.ee>
"""

__version__ = "01"

import Numeric,umath
from Numeric import *

def sqrt(a):
    try: return umath.sqrt(a)
    except ValueError: return umath.sqrt(a+0j)
def arcsin(a):
    try: return umath.arcsin(a)
    except ValueError: return umath.arcsin(a+0j)
def arccos(a):
    try: return umath.arccos(a)
    except ValueError: return umath.arccos(a+0j)
def ceil(a):
    try: return umath.ceil(a)
    except AttributeError: return umath.ceil(a.real)+1j*umath.ceil(a.imag)
def floor(a):
    try: return umath.floor(a)
    except AttributeError: return umath.floor(a.real)+1j*umath.floor(a.imag)
def fabs(a):
    try: return umath.fabs(a)
    except AttributeError: return umath.fabs(a.real)+1j*umath.fabs(a.imag) 
Numeric.__dict__['sqrt']=sqrt
Numeric.__dict__['arcsin']=arcsin
Numeric.__dict__['arccos']=arccos
Numeric.__dict__['ceil']=ceil
Numeric.__dict__['floor']=floor
Numeric.__dict__['fabs']=fabs

def test():
    for a in [-1,-1+0j,3.4,Numeric.array([2,3]),Numeric.array([-5,3j])]:
        print 'Numeric.sqrt(%s)=%s'%(`a`,`Numeric.sqrt(a)`)
        print 'Numeric.arcsin(%s)=%s'%(`a`,`Numeric.arcsin(a)`)
        print 'Numeric.arccos(%s)=%s'%(`a`,`Numeric.arccos(a)`)
    for a in [-1.5,-1+4.3j,Numeric.array([-5.2,3.7j])]:
        print 'Numeric.ceil(%s)=%s'%(`a`,`Numeric.ceil(a)`)
        print 'Numeric.floor(%s)=%s'%(`a`,`Numeric.floor(a)`)
        print 'Numeric.fabs(%s)=%s'%(`a`,`Numeric.fabs(a)`)

if __name__ == "__main__": test()