I'm trying to calculate the energy of a complex valued signal. Passing an array of complex numbers into the energy function, it separates the real and imaginary parts of the number and converts them into their polar equivalents. It then returns the sum of the squares of the real parts of each complex number. Everytime I try to call the energy function it says that the arctan2 ufunc is not supported for the input types.
def toExponential(a, b):
c = np.sqrt(a**2 + b**2)
d = np.arctan2(b,a)
return (c,d)
def energy(x):
sum = 0
for i in x:
e = ((i + np.conj(i))/2)
f = ((i - np.conj(i)/(1j * 2)))
r,i = toExponential(e,f)
sum = r**2 + sum
return sum
I think you are passing e and f to the to np.arctan2(b,a) ,instead of the real and imaginary parts of the complex number magnitude, phase = np.abs(i), np.angle(i)
Try this out
def energy(x):
sum = 0
for i in x:
magnitude, phase = np.abs(i), np.angle(i)
sum += magnitude**2
return sum
The magnitude and phase of each complex number are extracted in this example using the numpy.abs() and numpy.angle() methods, respectively. The energy of a complex signal is then determined by adding the squares of the complex numbers' magnitudes, which is the appropriate procedure.
If speed is important, here is a vectorized version of #MohamedFathallah's answer:
def energy(x):
return np.sum(np.abs(x)**2)
or
def energy(x):
return np.sum(np.real(x)**2 + np.imag(x)**2)
Related
I'm trying to make a function called cos_series that uses values x and nterms that gives me the sum of a series, using this equation 1 - x^2/2! + x^4/4! - x^6/6! +...
This is my code so far,
def cos_series(x,nterms):
lst = []
lst2 = []
for i in range(nterms):
lst+=[x**(2*i)/(math.factorial(i*2))]
for i in range(nterms):
lst2+=[(x**(2*i)/(math.factorial(i*2)))*-1]
return sum(lst2[1::2] + lst[::2])
cos_series(math.pi/3,3)
The return value should equal 0.501796 but I'm having trouble reaching it, can anyone help?
Your code seems to work just fine.
Your logic works with just:
def cos_series(x, n):
return sum((-1 if (i % 2) else 1) * x**(i*2) / math.factorial(i*2) for i in range(n))
Generating the sum of the series in one go and avoiding the computation of values you don't use.
(note that, after you changed your question, your code in fact returns 0.501796201500181 - which is the value you expected; there's no issue?)
You don't need to use math.factorial() and you don't need to store the terms in a list. Just build the numerator and denominator as you go and add up them up.
By producing the numerator and denominator iteratively, your logic will be much easier to manage and debug:
def cos(x,nTerms=10):
result = 0
numerator = 1
denominator = 1
for even in range(2,nTerms*2+1,2): # nTerms even numbers
result += numerator / denominator # sum of terms
numerator *= -x*x # +/- for even powers of x
denominator *= even * (even-1) # factorial of even numbers
return result
print(cos(3.141592653589793/3,3)) # 0.501796201500181
How can python be used for numerical finite difference calculation without using numpy?
For example I want to find multiple function values numerically in a certain interval with a step size 0.05 for a first order and second order derivatives.
Why don't you want to use Numpy? It's a good library and very fast for doing numerical computations because it's written in C (which is generally faster for numerical stuff than pure Python).
If you're curious how these methods work and how they look in code here's some sample code:
def linspace(a, b, step):
if a > b:
# see if going backwards?
if step < 0:
return linspace(b, a, -1*step)[::-1]
# step isn't negative so no points
return []
pt = a
res = [pt]
while pt <= b:
pt += step
res.append(pt)
return res
def forward(data, step):
if not data:
return []
res = []
i = 0
while i+1 < len(data):
delta = (data[i+1] - data[i])/step
res.append(delta)
i += 1
return res
# example usage
size = 0.1
ts = linspace(0, 1, size)
y = [t*t for t in ts]
dydt = forward(y, size)
d2ydt2 = forward(dydt, size)
Note: this will still use normal floating point numbers and so there are still odd rounding errors that happen because some numbers don't have an exact binary decimal representation.
Another library to check out is mpmath which has a lot of cool math functions like integration and special functions AND it allows you to specify how much precision you want. Of course using 100 digits of precision is going to be a lot slower than normal floats, but it is still a very cool library!
This code is a derivative code for a Taylor expansion that is 5 derivatives long. So ds(i) is supposed to replace its zero valued variables with the new x values (the derivative values). I keep getting the error "cannot assign function to call"
def derivatives(f, x, a, n):
f = f(x)
x = var
a = 1.0
n = 5
ds = np.zeros(n)
exp = f(x)
for i in range(n):
exp = sp.diff(exp,x)
ds(i) = exp.replace(x, a)
return ds
You probably meant ds[i], not ds(i). Square brackers for indexing vs round parentheses for function calls. That said, the code has other issues, from undefined var to using a NumPy array (?) to store SymPy objects. In general, it's advisable to keep in mind that SymPy works primarily with expressions not with functions. Expressions do not "take arguments", they are not like callable functions in Python.
And all of this is unnecessary, because SymPy computes n-th derivative on its own. Example, the 5th derivative of exp(2*x) at 0:
x = sp.symbols('x')
f = sp.exp(2*x) # an expression, not a function
n = 5
a = 0
print(f.diff(x, n).subs(x, a)) # take derivative n times, then plug a for x
prints 32. Or, if you want a Taylor expansion up to and including x**n:
print(f.series(x, a, n + 1))
prints 1 + 2*x + 2*x**2 + 4*x**3/3 + 2*x**4/3 + 4*x**5/15 + O(x**6).
I am trying to write a program using Python v. 2.7.5 that will compute the area under the curve y=sin(x) between x = 0 and x = pi. Perform this calculation varying the n divisions of the range of x between 1 and 10 inclusive and print the approximate value, the true value, and the percent error (in other words, increase the accuracy by increasing the number of trapezoids). Print all the values to three decimal places.
I am not sure what the code should look like. I was told that I should only have about 12 lines of code for these calculations to be done.
I am using Wing IDE.
This is what I have so far
# base_n = (b-a)/n
# h1 = a + ((n-1)/n)(b-a)
# h2 = a + (n/n)(b-a)
# Trap Area = (1/2)*base*(h1+h2)
# a = 0, b = pi
from math import pi, sin
def TrapArea(n):
for i in range(1, n):
deltax = (pi-0)/n
sum += (1.0/2.0)(((pi-0)/n)(sin((i-1)/n(pi-0))) + sin((i/n)(pi-0)))*deltax
return sum
for i in range(1, 11):
print TrapArea(i)
I am not sure if I am on the right track. I am getting an error that says "local variable 'sum' referenced before assignment. Any suggestions on how to improve my code?
Your original problem and problem with Shashank Gupta's answer was /n does integer division. You need to convert n to float first:
from math import pi, sin
def TrapArea(n):
sum = 0
for i in range(1, n):
deltax = (pi-0)/n
sum += (1.0/2.0)*(((pi-0)/float(n))*(sin((i-1)/float(n)*(pi-0))) + sin((i/float(n))*(pi-0)))*deltax
return sum
for i in range(1, 11):
print TrapArea(i)
Output:
0
0.785398163397
1.38175124526
1.47457409274
1.45836902046
1.42009115659
1.38070223089
1.34524797198
1.31450259385
1.28808354
Note that you can heavily simplify the sum += ... part.
First change all (pi-0) to pi:
sum += (1.0/2.0)*((pi/float(n))*(sin((i-1)/float(n)*pi)) + sin((i/float(n))*pi))*deltax
Then do pi/n wherever possible, which avoids needing to call float as pi is already a float:
sum += (1.0/2.0)*(pi/n * (sin((i-1) * pi/n)) + sin(i * pi/n))*deltax
Then change the (1.0/2.0) to 0.5 and remove some brackets:
sum += 0.5 * (pi/n * sin((i-1) * pi/n) + sin(i * pi/n)) * deltax
Much nicer, eh?
You have some indentation issues with your code but that could just be because of copy paste. Anyways adding a line sum = 0 at the beginning of your TrapArea function should solve your current error. But as #Blender pointed out in the comments, you have another issue, which is the lack of a multiplication operator (*) after your floating point division expression (1.0/2.0).
Remember that in Python expressions are not always evaluated as you would expect mathematically. Thus (a op b)(c) will not automatically multiply the result of a op b by c like you would expect with a mathematical expression. Instead this is the function call notation in Python.
Also remember that you must initialize all variables before using their values for assignment. Python has no default value for unnamed variables so when you reference the value of sum with sum += expr which is equivalent to sum = sum + expr you are trying to reference a name (sum) that is not binded to any object at all.
The following revision to your function should do the trick. Notice how I place multiplication operators (*) between every expression that you intend to multiply.
def TrapArea(n):
sum = 0
for i in range(1, n):
i = float(i)
deltax = (pi-0)/n
sum += (1.0/2.0)*(((pi-0)/n)*(sin((i-1)/n*(pi-0))) + sin((i/n)*(pi-0)))*deltax
return sum
EDIT: I also dealt with the float division issue by converting i to float(i) within every iteration of the loop. In Python 2.x, if you divide one integer type object with another integer type object, the expression evaluates to an integer regardless of the actual value.
A "nicer" way to do the trapezoid rule with equally-spaced points...
Let dx = pi/n be the width of the interval. Also, let f(i) be sin(i*dx) to shorten some expressions below. Then interval i (in range(1,n)) contributes:
dA = 0.5*dx*( f(i) + f(i-1) )
...to the sum (which is an area, so I'm using dA for "delta area"). Factoring out the 0.5*dx, makes the whole some look like:
A = 0.5*dx * ( (f(0) + f(1)) + (f(1) + f(2)) + .... + (f(n-1) + f(n)) )
Notice that there are two f(1) terms, two f(2) terms, on up to two f(n-1) terms. Combine those to get:
A = 0.5*dx * ( f(0) + 2*f(1) + 2*f(2) + ... + 2*f(n-1) + f(n) )
The 0.5 and 2 factors cancel except in the first and last terms:
A = 0.5*dx(f(0) + f(n)) + dx*(f(1) + f(2) + ... + f(n-1))
Finally, you can factor dx out entirely to do just one multiplication at the end. Converting back to sin() calls, then:
def TrapArea(n):
dx = pi/n
asum = 0.5*(sin(0) + sin(pi)) # this is 0 for this problem, but not others
for i in range(1, n-1):
asum += sin(i*dx)
return sum*dx
That changed "sum" to "asum", or maybe "area" would be better. That's mostly because sum() is a built-in function, which I'll use below the line.
Extra credit: The loop part of the sum can be done in one step with a generator expression and the sum builtin function:
def TrapArea2(n):
dx = pi/n
asum = 0.5*(sin(0) + sin(pi))
asum += sum(sin(i*dx) for i in range(1,n-1))
return asum*dx
Testing both of those:
>>> for n in [1, 10, 100, 1000, 10000]:
print n, TrapArea(n), TrapArea2(n)
1 1.92367069372e-16 1.92367069372e-16
10 1.88644298557 1.88644298557
100 1.99884870579 1.99884870579
1000 1.99998848548 1.99998848548
10000 1.99999988485 1.99999988485
That first line is a "numerical zero", since math.sin(math.pi) evaluates to about 1.2e-16 instead of exactly zero. Draw the single interval from 0 to pi and the endpoints are indeed both 0 (or nearly so.)
I am trying to Write a function called sum_square_difference which takes a number n and returns the difference between the sum of the squares of the first n natural numbers and the square of their sum.
I think i know how to write a function that defines the sum of squares
def sum_of_squares(numbers):
total = 0
for num in numbers:
total += (num ** 2)
return(total)
I have tried to implement a square of sums function:
def square_sum(numbers):
total = 0
for each in range:
total = total + each
return total**2
I don't know how to combine functions to tell the difference and i don't know if my functions are correct.
Any suggestions please? I am using Python 3.3
Thank you.
The function can be written with pure math like this:
Translated into Python:
def square_sum_difference(n):
return int((3*n**2 + 2*n) * (1 - n**2) / 12)
The formula is a simplification of two other formulas:
def square_sum_difference(n):
return int(n*(n+1)*(2*n+1)/6 - (n*(n+1)/2)**2)
n*(n+1)*(2*n+1)/6 is the formula described here, which returns the sum of the squares of the first n natural numbers.
(n*(n+1)/2))**2 uses the triangle number formula, which is the sum of the first n natural numbers, and which is then squared.
This can also be done with the built in sum function. Here it is:
def sum_square_difference(n):
r = range(1, n+1) # first n natural numbers
return sum(i**2 for i in r) - sum(r)**2
The range(1, n+1) produces an iterator of the first n natural numbers.
>>> list(range(1, 4+1))
[1, 2, 3, 4]
sum(i**2 for i in r) returns the sum of the squares of the numbers in r, and sum(r)**2 returns the square of the sum of the numbers in r.
# As beta says,
# (sum(i))^2 - (sum(i^2)) is very easy to calculate :)
# A = sum(i) = i*(i+1)/2
# B = sum(i^2) = i*(i+1)*(2*i + 1)/6
# A^2 - B = i(i+1)(3(i^2) - i - 2) / 12
# :)
# no loops... just a formula !**
This is a case where it pays to do the math beforehand. You can derive closed-form solutions for both the sum of the squares and the square of the sum. Then the code is trivial (and O(1)).
Need help with the two solutions?
def sum_square_difference(n):
r = range(1,n+1)
sum_of_squares = sum(map(lambda x: x*x, r))
square_sum = sum(r)**2
return sum_of_squares - square_sum
In Ruby language you can achieve this in this way
def diff_btw_sum_of_squars_and_squar_of_sum(from=1,to=100) # use default values from 1..100.
((1..100).inject(:+)**2) -(1..100).map {|num| num ** 2}.inject(:+)
end
diff_btw_sum_of_squars_and_squar_of_sum #call for above method