Problem calling math.cos()

Felipe Almeida Lessa felipe.lessa at gmail.com
Sat Apr 22 16:10:47 EDT 2006


Em Sáb, 2006-04-22 às 15:14 -0400, Sambo escreveu:
> when I import it (electronics) in python.exe in windows2000 and 
> try to use it, it croaks.  ??? 

$ python2.4
Python 2.4.3 (#2, Mar 30 2006, 21:52:26)
[GCC 4.0.3 (Debian 4.0.3-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 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]
...
>>> ac_add_a_ph(10, 0, 6, 45)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 10, in ac_add_a_ph
AttributeError: 'module' object has no attribute 'abs'
>>> abs
<built-in function abs>
>>> def ac_add_a_ph(amp1, ph1, amp2, ph2):
...     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
...     ph3 = math.atan(ac3.imag / ac3.real)
...     return [abs(amp3), ph3]
...
>>> ac_add_a_ph(10, 0, 6, 45)
[14.86111751324192, 0.28951347254362308]




So:
-------------------------------
import math

def polar(rho, theta, theta_in_radians=False)
    """Creates a complex number from its polar form."""
    # Avoid repeating yourself by creating different functions
    if not theta_in_radians:
        theta = math.radians(theta)
    return complex(rho * math.cos(theta), rho * math.sin(theta))

def ac_add_a_ph(amp1, ph1, amp2, ph2):
    """Add two complexes together from their polar form."""
    # You don't have to initialize the variables with "0.0" and such.
    ac3 = polar(amp1, ph1) + polar(amp2, ph2)
    ph3 = math.atan(ac3.imag / ac3.real)
    return (abs(ac3), ph3) # Use a tuple in this case
--------------------------------------



*But*, I encourage you using the complex numbers themselves instead of
converting to and from over and over.


HTH,

-- 
Felipe.




More information about the Python-list mailing list