Problem calling math.cos()

Roy Smith roy at panix.com
Sat Apr 22 15:45:25 EDT 2006


In article <3ev2g.9680$%97.5795 at newsfe15.lga>, Sambo <sambo at void.com> 
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
> >>>

That's not what I get when I run it (admittedly, not on windows).  I get:

>>> 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 "electronics.py", line 13, in ac_add_a_ph
    amp3 = math.abs( ac3 )
AttributeError: 'module' object has no attribute 'abs'
>>> 

which is exactly what I expected, since abs (which is indeed absolute 
value) is a built-in function, not a part of the math module.  Are you sure 
the stack trace you posted matches the source code you posted?

By the way, when using math functions, I find it's usually easier to import 
them into my namespace by doing "from math import *", then I can just use 
sin(), cos(), etc directly, instead of having to do math.sin() or 
math.cos().  Especially for common math functions, this makes your code a 
lot easier to read.



More information about the Python-list mailing list