Problem calling math.cos()
Robert Kern
robert.kern at gmail.com
Sat Apr 22 15:55:26 EDT 2006
Sambo wrote:
> I have the following module:
> -------------------------------
> import math
>
> def ac_add_a_ph( amp1, ph1, amp2, ph2 ):
>
> amp3 = 0.0
> ph3 = 0.0
> ac1 = ( 0, 0j )
> ac2 = ( 0, 0j )
> ac3 = ( 0, 0j )
> ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * math.sin( math.radians( ph1 ) ) )
> ac2 = complex( amp2 * math.cos( math.radians( ph2 ) ), amp2 * math.sin( math.radians( ph2 ) ) )
> ac3 = ac1 + ac2
> amp3 = math.abs( ac3 )
> ph3 = math.atan( ac3.imag / ac3.real )
> return [amp3, ph3]
> --------------------------------------
> when I import it (electronics) in python.exe in windows2000 and
> try to use it, it croaks. ???
>
>>>>import math
>>>>import electronics
>>>>print electronics.ac_add_a_ph( 10, 0 , 6 , 45 )
>
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> File "f:\devel\python\electronics.py", line 10, in ac_add_a_ph
> ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * math.sin( math
> .radians( ph1 ) ) )
> NameError: global name 'cos' is not defined
>
> global?? huh?
That's not what I get.
[~]$ cat electronics.py
import math
def ac_add_a_ph( amp1, ph1, amp2, ph2 ):
amp3 = 0.0
ph3 = 0.0
ac1 = ( 0, 0j )
ac2 = ( 0, 0j )
ac3 = ( 0, 0j )
ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * math.sin(
math.radians( ph1 ) ) )
ac2 = complex( amp2 * math.cos( math.radians( ph2 ) ), amp2 * math.sin(
math.radians( ph2 ) ) )
ac3 = ac1 + ac2
amp3 = math.abs( ac3 )
ph3 = math.atan( ac3.imag / ac3.real )
[~]$ python
Python 2.4.1 (#2, Mar 31 2005, 00:05:10)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import electronics
>>> electronics.ac_add_a_ph(10, 0, 6, 45)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "electronics.py", line 13, in ac_add_a_ph
amp3 = math.abs( ac3 )
AttributeError: 'module' object has no attribute 'abs'
>>>
> what does abs stand for? why is that not absolute value? hmmm.
> Hmm, complex numbers, cool I don't even have any idea where C
> stands on this.
Change math.abs() to abs(). It's a builtin function. Yes, it does compute the
absolute value. Fixing that:
>>> import electronics
>>> electronics.ac_add_a_ph(10, 0, 6, 45)
[14.861117513241918, 0.2895134725436232]
>>>
--
Robert Kern
robert.kern at gmail.com
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list