473,321 Members | 1,877 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,321 software developers and data experts.

why no arg, abs methods for comlex type?

Hello all,

I often have to deal with complex numbers
using python iteractive as calculator

I wonder why there are no methods like arg, abs

well one can use
c = 1+1j
abs(c)

In my opinion it would also be nice to have the
possibility to write it as
c.abs()
it looks more OO

unfortunately there is no arg method to get the angle
of the complex number
of course it easy to write one on your own
(that's what I have done for myself)
but differnt people will create and reinvite the wheel
over and over again
while reading alien code one will have to spend 2 seconds
remembering the function names etc

consider
c = 1+1j
c.arg(angle_mode = cmath.GRAD) -> 45.0
or
c.arg(angle_mode = cmath.RAD) -> 0.7853..

I would also like to see some more functions to make
calculations with complex number more convenient
e.g.
c = 27
c.pow(numerator = 1, denominator = 3,
mode = cmath.EULER, angle_mode = cmath.GRAD)
-> ((3,0), (3,120), (3,240))

what do you think about it?
maybe there exists some proposals aiming this goal?

--
Daniel
Aug 5 '05 #1
18 2178
> I would also like to see some more functions to make
calculations with complex number more convenient
e.g.
c = 27


c = 27+0j
Aug 5 '05 #2

"Daniel Schüle" <uv**@rz.uni-karlsruhe.de> wrote in message
news:dc**********@news2.rz.uni-karlsruhe.de...
I wonder why there are no methods like arg, abs well one can use
c = 1+1j
abs(c)

In my opinion it would also be nice to have the
possibility to write it as
c.abs()
it looks more OO
Python is object based but not rigidly OO in syntax or looks. This is an
intentional design decision. Not being gratuitiously redundant is another.
unfortunately there is no arg method to get the angle
of the complex number
I agree that this is a deficiency. I would think .angle() should be a
no-param method like .conjugate(), though its internal implementation would
need access to the appropriate cmath functions. I think returning radians
might be enough though. You could submit to the SourceForge tracker a RFE
(Request For Enhancement) if not a patch.
I would also like to see some more functions to make
calculations with complex number more convenient
e.g.
c = 27
c.pow(numerator = 1, denominator = 3,
mode = cmath.EULER, angle_mode = cmath.GRAD)
-> ((3,0), (3,120), (3,240))
Wanting all roots is fairly specialized. sqrt(4) is 2, not (2, -2).
what do you think about it?
maybe there exists some proposals aiming this goal?


Have you looked for complex math functions in numpy, numarray, scipy or
similar packages? It is possible that a cmath2 module, written in Python,
could be useful.

Terry J. Reedy


Aug 5 '05 #3
On Fri, 05 Aug 2005 15:42:41 +0200,
Daniel Schüle <uv**@rz.uni-karlsruhe.de> wrote:
Hello all,
I often have to deal with complex numbers
using python iteractive as calculator I wonder why there are no methods like arg, abs well one can use
c = 1+1j
abs(c) In my opinion it would also be nice to have the
possibility to write it as
c.abs()
it looks more OO
I guess it's for the same reason that we are spared
from writing things like this:

z = x.squared().added_to(y.squared()).squareroot()
E = m.multiplied_by(c.squared())

More OO, yes. More readable, not IMO.
I would also like to see some more functions to make
calculations with complex number more convenient
[ ... ]
maybe there exists some proposals aiming this goal?


SciPy or Numeric?

Regards,
Dan

--
Dan Sommers
<http://www.tombstonezero.net/dan/>
Aug 5 '05 #4
Terry Reedy wrote:
"Daniel Schüle" <uv**@rz.uni-karlsruhe.de> wrote in message
news:dc**********@news2.rz.uni-karlsruhe.de...

....
unfortunately there is no arg method to get the angle
of the complex number


I agree that this is a deficiency. I would think .angle() should be a
no-param method like .conjugate(), though its internal implementation would
need access to the appropriate cmath functions.


You need math, not cmath.

def arg(z):
"""The Argument of z, in radians."""
z += 0j # make it work on real inputs
return math.atan2(z.imag, z.real)

Aug 5 '05 #5
On Fri, 05 Aug 2005 15:42:41 +0200, Daniel Schüle
<uv**@rz.uni-karlsruhe.de> declaimed the following in comp.lang.python:

c = 1+1j
c.arg(angle_mode = cmath.GRAD) -> 45.0
Is that right? The result looks more like Degrees...

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Aug 5 '05 #6
Hi Terry,
In my opinion it would also be nice to have the
possibility to write it as
c.abs()
it looks more OO

Python is object based but not rigidly OO in syntax or looks. This

is an intentional design decision. Not being gratuitiously redundant is another.

I agree, redundancy confuses people
unfortunately there is no arg method to get the angle
of the complex number

I agree that this is a deficiency. I would think .angle() should be a
no-param method like .conjugate(), though its internal implementation

would need access to the appropriate cmath functions. I think returning radians might be enough though.
I don't know what nomenclature is used in english speaking
mathematical world for angle of a complex number
I learned it in german as Arg(z) .. Arg standing for argument
you see, we would have named it differently, hence making
it difficult for the reader, eventually creating redundancy
You could submit to the SourceForge tracker a RFE
(Request For Enhancement) if not a patch.
I never did, but I will see
c = 1 + 1j
def arg(c, angle_mode = "RAD"): .... if angle_mode not in ("RAD", "GRAD"):
.... raise ValueError
.... import math
.... ret = math.atan2(c.imag, c.real)
.... if angle_mode == "GRAD":
.... return ret / math.pi * 180
.... return ret

it's pretty easy and straightforward implementation
while writing this, I was struck by an idea and
reimplemented it as following
def arg(self, angle_mode = "RAD"): .... if angle_mode not in ("RAD", "GRAD"):
.... raise ValueError
.... import math
.... ret = math.atan2(self.imag, self.real)
.... if angle_mode == "GRAD":
.... return ret / math.pi * 180
.... return ret
.... class Complex(complex): pass
Complex.arg = arg
c = Complex(1+1j)
c.arg(angle_mode = "GRAD")
45.0

later I realized that this represents "yet another implementation"
which could be done by someone, thus again leading to possible
redundancy and confuse people

all this would not have happened when we would have
arg or angle builtin in complex type

I would also like to see some more functions to make
calculations with complex number more convenient
e.g.
c = 27
c.pow(numerator = 1, denominator = 3,
mode = cmath.EULER, angle_mode = cmath.GRAD)
-> ((3,0), (3,120), (3,240))

Wanting all roots is fairly specialized. sqrt(4) is 2, not (2, -2).


it could be named .allroots(n) -> ((), (), ())
with n whole number

indeed .pow() is not a good name for it, since z**x
always yields one complex number

if x is 2.5 or alike, it could be aproximated with n/m and use
res = []
for i in z.allroots(m):
res.append(i**n)

I am not sure, this is correct iterpretation of z**2.5
I will need to ask in math newsgroup :)
and approximation might not be good enough
Have you looked for complex math functions in numpy, numarray, scipy or
similar packages? It is possible that a cmath2 module, written in Python, could be useful.


I hope so
I will google for cmath2, I never heard about it
I am new to Numeric and numarray, I was playing with them and
ufunc-tionsand matplotlab, as for SciPy I couldnt find
any binary for 2.4 Python unfortunately :-/

Regards

--
Daniel
Aug 5 '05 #7
>>c = 1+1j
c.arg(angle_mode = cmath.GRAD) -> 45.0

Is that right? The result looks more like Degrees...


maybe I confuse, in german one would say "45 Grad"
I took a freedom to translate it directly :)
well, my calculator shows a "D"
which most likely stands for Degree, I cannot tell for sure

--
Daniel
Aug 5 '05 #8
Daniel Schüle wrote:
what do you think about it?
maybe there exists some proposals aiming this goal?


Derive your own subclass of complex and define those methods.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
I am not afraid / To be a lone Bohemian
-- Lamya
Aug 5 '05 #9
Daniel Schüle wrote:
maybe I confuse, in german one would say "45 Grad"
I took a freedom to translate it directly :)
well, my calculator shows a "D"
which most likely stands for Degree, I cannot tell for sure


Probably. In English, you have degrees and gradians, which aren't the
same thing; gradians are defined so that there are 400 gradians in a
circle (so 100 gradians in a right angle).

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
I am not afraid / To be a lone Bohemian
-- Lamya
Aug 5 '05 #10
Erik Max Francis wrote:
Daniel Schüle wrote:
maybe I confuse, in german one would say "45 Grad"
I took a freedom to translate it directly :)
well, my calculator shows a "D"
which most likely stands for Degree, I cannot tell for sure


Probably. In English, you have degrees and gradians, which aren't the
same thing; gradians are defined so that there are 400 gradians in a
circle (so 100 gradians in a right angle).


In German, they're "Altgrad" (degrees) and "Neugrad" or "Gon" (gradians).

Reinhold
Aug 5 '05 #11

"Daniel Schüle" <uv**@rz.uni-karlsruhe.de> wrote in message
news:dd**********@news2.rz.uni-karlsruhe.de...
I agree that this is a deficiency. I would think .angle() should be a


I don't know what nomenclature is used in english speaking
mathematical world for angle of a complex number
I learned it in german as Arg(z) .. Arg standing for argument
you see, we would have named it differently, hence making
it difficult for the reader, eventually creating redundancy


I am aware of the usage of argument to mean the angle in polar
representation, but I don't like it. The word argument already has two
other meanings, one in common English, the other in math/CS. The latter
meaning is the inputs to a function, and that is how the word is used in
Python (though the former applies more to many c.l.p threads ;-) To me,
the polar angle has no connection with either meaning and so the usage is
'like Greek' to me. Whereas angle is exactly what it is.

As for Greek: I first learned r(adius),theta (versus x,y or real,imag) as
the names for polar coordinates or the polar representation for complex
numbers and only ran into arg much later in some contexts. And I have seen
complex number implementations that use the equivalent of c.r() and
c.theta(). But I did not suggest that for one of the reasons I don't like
'lambda': its fine if you already know it and arbitrary if you don't. (Is
theta used in Germany?)
It is possible that a cmath2 module, written in Python, could be
useful.


I hope so
I will google for cmath2, I never heard about it


That is because we have not written it yet. The allroots function could be
the first addition, if it is not present elsewhere. The 'could be' was
meant in the sense of 'if someone were to write it' rather than 'if you
were to read it' ;-)

Terry J. Reedy

Aug 5 '05 #12
[...]
Derive your own subclass of complex and define those methods.


I think something as basic as an angle/arg of complex number
definetly belongs to the interface, and it would not even require a
great effort to put it there

most complex formulas out there use Euler representation
it's a waste of code lines (and programmers time)
to write 3 liner functions for the transformion between
a+bj <-> (r,angle)
Python makes things covenient
so we have complex numbers in the core language
the calculations where perfectly possible without them
using (re, im) tupels and many many sin/cos in the code
but imagine how ugly it would be ..
I would like see Python as a competitor to Matlab etc

Regards

--
Daniel

Aug 5 '05 #13
[...]
I am aware of the usage of argument to mean the angle in polar
representation, but I don't like it. The word argument already has two
other meanings, one in common English, the other in math/CS. The latter
meaning is the inputs to a function, and that is how the word is used in
Python (though the former applies more to many c.l.p threads ;-) To me,
the polar angle has no connection with either meaning and so the usage is
'like Greek' to me. Whereas angle is exactly what it is.
..angle() would be also alright, as it is easy to grasp
As for Greek: I first learned r(adius),theta (versus x,y or real,imag) as
the names for polar coordinates or the polar representation for complex
numbers and only ran into arg much later in some contexts. And I have seen
complex number implementations that use the equivalent of c.r() and
c.theta(). But I did not suggest that for one of the reasons I don't like
'lambda': its fine if you already know it and arbitrary if you don't. (Is
theta used in Germany?)


yes, of course
the entire mathematic is full of them :)
as for the complex numbers, in our lessons we used R(adius) and
Phi for the angle for polar representation
I guess it's more a question of teacher's preference than a national
norm
Aug 5 '05 #14
On Fri, 05 Aug 2005 18:24:26 +0200, Daniel Schüle
<uv**@rz.uni-karlsruhe.de> declaimed the following in comp.lang.python:
c = 1+1j
c.arg(angle_mode = cmath.GRAD) -> 45.0

Is that right? The result looks more like Degrees...


maybe I confuse, in german one would say "45 Grad"
I took a freedom to translate it directly :)
well, my calculator shows a "D"
which most likely stands for Degree, I cannot tell for sure


45 Degrees => 50 Grad

2PI => 360 Degree => 400 Grad

(and military protractors are the only place I've seen Grads
used)
-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Aug 6 '05 #15
Daniel Schüle wrote:
[...]
> Derive your own subclass of complex and define those methods.
I think something as basic as an angle/arg of complex number
definetly belongs to the interface, and it would not even require a
great effort to put it there


<shrug> Okay. Write a patch. Personally, I would prefer that it be a
function in cmath rather than a method because then it could be made to
work on integers and regular floats, too.
most complex formulas out there use Euler representation
it's a waste of code lines (and programmers time)
to write 3 liner functions for the transformion between
a+bj <-> (r,angle)
It's a very, very tiny outlay of effort on the programmer's part that
only has to happen once in their career.
Python makes things covenient
so we have complex numbers in the core language
the calculations where perfectly possible without them
using (re, im) tupels and many many sin/cos in the code
but imagine how ugly it would be ..
I don't have to imagine. It's not all that ugly.
I would like see Python as a competitor to Matlab etc


I think it is already.

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Aug 6 '05 #16
[...]
<shrug> Okay. Write a patch. Personally, I would prefer that it be a
function in cmath rather than a method because then it could be made to
work on integers and regular floats, too.


Ok, but what semantic should angle/arg have, say for 3 respectively
for 3.0?
the same as for arg(3+0j)?
Aug 6 '05 #17
Daniel Schüle wrote:
<shrug> Okay. Write a patch. Personally, I would prefer that it be a
function in cmath rather than a method because then it could be made
to work on integers and regular floats, too.


Ok, but what semantic should angle/arg have, say for 3 respectively
for 3.0?
the same as for arg(3+0j)?


As a potential user, that's what I would expect.

See Dan Bishop's implementation (earlier in this thread).
Aug 6 '05 #18
On Sat, 06 Aug 2005 06:44:03 GMT, Dennis Lee Bieber <wl*****@ix.netcom.com> wrote:
On Fri, 05 Aug 2005 18:24:26 +0200, Daniel Schüle
<uv**@rz.uni-karlsruhe.de> declaimed the following in comp.lang.python:
>>c = 1+1j
>>c.arg(angle_mode = cmath.GRAD) -> 45.0
>
>
> Is that right? The result looks more like Degrees...


maybe I confuse, in german one would say "45 Grad"
I took a freedom to translate it directly :)
well, my calculator shows a "D"
which most likely stands for Degree, I cannot tell for sure


45 Degrees => 50 Grad

2PI => 360 Degree => 400 Grad

(and military protractors are the only place I've seen Grads
used)

No one seems to have mentioned 2PI => 1 circle as in unit circles.
IIRC, back in the day before math chips, we implemented all the trig
functions in terms of angles where some number of bits respresented
one circle, for best resolution of angles with a given number of bits.
Also for compatibility with angular input devices. Also for the natural
modulo 2PI effect of representing an angle as an int, with unsigned interval
[0..2PI) or signed interval [-PI..PI). IIRC, FFTs involve phase in steps of
2PI/2**n also (for power-of-2 decimation effectively dividing the unit circle
in terms of powers of e**-i*(2*pi/2**n)) (where i is imaginary 0+1j). Hm, let' see,
for 45-degree deltas (2PI/2**3) ...
import cmath
(cmath.e+0j)**(-2j*cmath.pi/2**3) (0.70710678118654757-0.70710678118654746j)
for c in [((cmath.e+0j)**(-2j*cmath.pi/2**3))**i for i in xrange(8)]: print c

...
(1+0j)
(0.707106781187-0.707106781187j)
(1.5701957963e-016-1j)
(-0.707106781187-0.707106781187j)
(-1-3.1403915926e-016j)
(-0.707106781187+0.707106781187j)
(-4.71058738891e-016+1j)
(0.707106781187+0.707106781187j)

Regards,
Bengt Richter
Aug 6 '05 #19

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

99
by: David MacQuigg | last post by:
I'm not getting any feedback on the most important benefit in my proposed "Ideas for Python 3" thread - the unification of methods and functions. Perhaps it was buried among too many other less...
5
by: Irmen de Jong | last post by:
Hi, I've developed the Metaclass below, because I needed a way to make a bunch of classes thread-safe. I didn't want to change every method of the class by adding lock.aqcuire()..lock.release()...
51
by: Noam Raphael | last post by:
Hello, I thought about a new Python feature. Please tell me what you think about it. Say you want to write a base class with some unimplemented methods, that subclasses must implement (or...
32
by: Adrian Herscu | last post by:
Hi all, In which circumstances it is appropriate to declare methods as non-virtual? Thanx, Adrian.
3
by: Jay | last post by:
Why are there static methods in C#. In C++ static was applied to data only (I believe) and it meant that the static piece of data was not a part of the object but only a part of the class (one...
4
by: Alex Sedow | last post by:
Method invocation will consist of the following steps: 1. Member lookup (14.3) - evaluate method group set (Base.f() and Derived.f()) .Standart say: "The compile-time processing of a method...
33
by: Joe Fallon | last post by:
1. I have a Base class that has a certain amount of functionality. 2. Then I have a CodeSmith generated class that inherits from the Base class and adds functionality. 3. Since I want to be able...
10
by: r035198x | last post by:
The Object class has five non final methods namely equals, hashCode, toString, clone, and finalize. These were designed to be overridden according to specific general contracts. Other classes that...
318
by: King Raz | last post by:
The shootout site has benchmarks comparing different languages. It includes C# Mono vs Java but not C# .NET vs Java. So I went through all the benchmark on the site ... ...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.