Good day,
I am trying to write a function for the following equation:
Where B and N are given and I am solving for A.
I was reading up and it seemed like sympy was the way to go so I started to declare the known variables, but when it came to the sigma notation with the factorial, I had no idea of how to approach it since A is an unknown.
Here is what I came up with:
from sympy import Eq, var, solve
from math import *
A = var('A')
channels = raw_input("Enter the number of channels: ")
#GOS = raw_input("Enter GOS: ")
Sigma = A
for i in range(0,channels+1):
Sigma += (A**i / factorial(i))
# equation = Eq((A**channels / factorial(channels)) / Sigma)
# print solve(equation)
which gives me the error TypeError: cannot concatenate 'str' and 'int' objects
This makes sense to me, but my lack of knowledge with sympy makes me unable to figure out how to fix it.
EDIT: Looking around a bit more, I edited my code to this:
from sympy import *
A = symbols('A')
channels = raw_input("Enter the number of channels: ")
GOS = raw_input("Enter GOS: ")
Sigma = summation(A**i / factorial(i), (i, 0,channels))
print Sigma
# equation = Eq((A**channels / factorial(channels)) / Sigma)
Now I get NameError: name 'i' is not defined
Thanks in advance.
First of all, the error ( name 'i' not defined) is because you havent defined it. so you need to give an initial value for i.
secondly, I have tried to make your program run. got an error free solution with this code:
from sympy import *
A = symbols('A')
channels = raw_input("Enter the number of channels: ")
GOS = raw_input("Enter GOS: ")
# note that I convert the string 'channel' to an int
# convert to float if channel could also be a floating number
channels = int(channels)
Sigma = A
for i in range(0,channels+1):
Sigma += (A**i / factorial(i))
print Sigma
The result,
inputs: channels = 3, GOS = 1
output: A**3/6 + A**2/2 + 2*A + 1
EDIT: Out of interest I started looking further into your problem (also because I could realize this question would not stop just by a datatype issue).
The Solve function has 2 inputs, the equation and the symbol to calculate.
it solves the equation == 0. so the variable B has to be subtracted from the equation. (I supposed the input GOS is the B variable in the function)
equation = (A**channels / factorial(channels)) / Sigma
print(solve(equation-int(GOS), A))
running the code with the lines above (add them under the code) gave these outputs:
A**3/6 + A**2/2 + 2*A + 1
[-2 - sqrt(2), -2 + sqrt(2)]
I must notice that if the GOS does not intersect the function it gives large results with additional parameter I (capital i, might indicate imaginary i).
I hoped this helped solving your problem.
To describe a similar sum as at the top of the page, when I use the asmeurer's recommendation summation, I get the error -TypeError: 'Symbol' object is not subscriptable." What could be the possible cause of this error? I imported the libraries below. There is a continuation of the code, but I did not add it to avoid confusion.
import sympy as sympy
from sympy import *
from sympy import summation, symbols
class FQ():
def integrate(self):
for k in range(1, self.Nt):
i = symbols('i', integer=True)
self.Sigma = summation(self.u[i+1][j], (i, 0, k - 1))
#second attempt
def integrate(self, alpha, Nt, Nx, L):
for k in range(1, self.Nt):
for j in range(1, self.Nx-1):
#define sum
for i in range(1, self.Nt):
Sigma = summation(u[i+1][j], (i, 0, k-1))
You can also perform the summation in SymPy using the summation function
i = symbols('i')
summation(A**i/factorial(i), (i, 0, N)
Another note: you are starting with Sigma = A, meaning your final result is A + ΣA^i/i! instead of just ΣA^i/i! (you can see in the output from #Petrus1904's answer there is a 2*A instead of A). If you want to use a loop to compute a summation you should initialize the variable to 0.
Related
New to calculus and not sure where this goes...
I'm trying to compute the Riemann-Liouville interpretation of the integral in Python using sympy. However the resulting integral when running my code between 0 and T contains T as a variable, which I do not want. What should I do to fix this?
Code:
def integral(f, order):
gamma_recip = 1/gamma(order)
T = sympy.Symbol('T')
r = sympy.Symbol('r')
eq = (T-r) ** order - 1
function_eq = eq * f(r)
integral = sympy.integrate(function_eq, (r, 0, T))
return integral
Equation:
Sample call as requested:
-0.333333333333333*T**3 + 0.0833333333333333*T**4.0
Function and order used:
def f(x):
return x**2
print(integral(f, 1.0))
Expected result:
r**3/3
Two issues:
you are using "T" as the integral limit so you will end up with that in the result; if you want "r" in the result, swap the use of T and r in your function
you didn't put parentheses around the order - 1 in your definition of eq; if you do you will (with your current code) get the expected T**3/3
I'm new to programming and I'm having a hard time solving this equation using Python.
I would like for the system to give me the value for X.
((X-5)/(2) + (X/4) + (X-12)/(3))
Sympy looks promising, especially section 3.2.4, "Equation Solving".
Assuming your right hand side of equation is some given value or expression:
import sympy as sym
x = sym.Symbol("x")
RHS = 13
LHS = (x - 5)/2 + x/4 + (x - 12)/3
eqn = LHS - RHS
soln = sym.solve(eqn, x)
print(soln)
This yields the solution x = 18. Replace RHS with your own value or expression. If there is nothing, simply put RHS to be 0; which gives the solution x = 6.
If you want to solve your equation step by step, you are still going to need SymPy:
https://docs.sympy.org/latest/install.html
Here is a simple polynomial equation:
b^2 + 2b + 1 = 0
I could easily solve this as:
import numpy as np
from scipy.optimize import fsolve
eq = lambda b : np.power(b,2) + 2*b + 1
fsolve(eq, np.linspace(0,1,2))
Similarly I could solve any equation, that has finite number of terms. But how do I solve an equation with infinite number of terms which is given as :
The above equation could be written as :
5 = (1 - l) * (5.5 + 4.0*l + 4*l^2 + 6*l^3 + 5*l^4 + 5*l^5 + 5*l^6 + 5*l^7 + 5*l^8 + 5*l^9 + 5*l^10 )
when n goes from 1 to 10. But I want to solve this for sufficiently large value of n such that LHS ~= RHS.
I know the values of LHS and G1 -> Ginf but cannot understand how could I compute the value of lambda here.
I tried looking at numpy polynomial functions but could not find a function that is relevant here.
The following glosses over the fact that I do not 100% understand the coefficient notation G_t:t+n (what kind of dependency is that supposed to indicate exactly?)
Obviously, the solution will depend on coefficients. If as your example suggests, the coefficients are all equal above some index n_0 then your r.h.s. expression is a telescoping sum and equal to G_t:1 + sum_1^n_0 [G_t:n - G_t:n+1] l^n`. Be sure to note that this sum is finite, so you know how to proceed from here.
One caveat: you must have |l| < 1 otherwise the series does not converge and the r.h.s. is undefined, although some kind of continuation argument may be possible.
I am translating my code from Python to Mathematica. I am trying to define a matrix, whose values depend on a variable chosen by the user, called kappa.
In Python the code looked like that:
def getA(kappa):
matrix = zeros((n, n), float)
for i in range(n):
for j in range(n):
matrix[i][j] = 2*math.cos((2*math.pi/n)*(abs(j-i))*kappa)
n = 5
return matrix
What I have done so far in Mathematica is the following piece of code:
n = 5
getA[kappa_] :=
A = Table[0.0, {n}, {n}];
For[i = 0, i < n, i++,
For[ j = 0, j < n, j++,
A[[i, j]] = 2*Cos[(2*pi/n)*(abs (j - i))*kappa]]];
b = getA[3]
But when I try to evaluate this matrix for a value of kappa equal to 3, I get the following error:
Set::partd: "Part specification A[[i,j]] is longer than depth of object.
How can I fix it?
Try something like this
n = 5;
A = Table[2*Cos[(2 \[Pi]/n) (Abs[ j - i]) \[Kappa]], {i, 1, n}, {j, 1, n}];
b = A /. \[Kappa]->3
I'll leave you to package this into a function if you want to.
You write that you are trying to translate Python into Mathematica; your use of For loops suggests that you are trying to translate to C-in-Mathematica. The first rule of Mathematica club is don't use loops.
Besides that you've made a number of small syntactical errors, such as using abs() where you should have had Abs[] (Mathematica's built-in functions all have names beginning with a capital letter, they wrap their arguments in [ and ], not ( and )), pi is not the name of the value of the ratio of a circle's diameter to its radius (it's called \[Pi]). Note too that I've omitted the multiplication operator which is often not required.
In your particular case, this would be the fastest and the most straightforward solution:
getA[κ_, n_] := ToeplitzMatrix[2 Cos[2 π κ Range[0, n - 1] / n]]
Our assignment is to use sympy to evaluate the exact definite integral of a function and then compare it with the approximation of the definite integral obtained from another python function we wrote. With simple polynomial functions my code works fine, but with a complicated sine function it keeps either breaking or returning nan.
from numpy import *
def simpson(f,a,b,n):
if n<=0 or n%2!=0:
print('Error: the number of subintervals must be a positive even number')
return float('NaN')
h = float(b - a) / float(n)
x = arange(a,b+h,h)
fx = f(x)
fx[1:n:2] *= 4.0
fx[2:n:2] *= 2.0
return (h/3.)*sum(fx)
this is in one file (simpandtrap) and gives the approximation for the definite integral of f from a to b using a simpson's rule approximation with n subintervals
from pylab import *
def s(x):
return x*sin(3./(x+(x==0)))
This is the function giving me trouble, in a file called assignment8functions
import assignment8functions as a
import SimpAndTrap as st
import sympy as sp
x = sp.symbols('x')
Exact_int_q = sp.integrate(a.q(x),(x,0,2)).evalf(25)
Exact_int_s = sp.integrate(x*sp.sin(3./(x)),(x,0,2)).evalf(25)
q(x) is another function we're supposed to use that everything works fine for - it's just a polynomial. When I try to do the integration the same way it breaks, so I had to put the function for s(x) directly into the call instead of importing the one from the other file
n = a.array([10,100,1000,10000,10000,1000000])
s_error_simp_array = a.zeros(6)
for i in a.arange(6):
s_error_simp_array[i] = abs(Exact_int_s - st.simpson(a.s,0,2,n[i])
here I try to find the error in the approximation. the problem is first of all that Exact_int_s is apparently -4.5*Si(zoo) + 8.16827746848576, and I have no idea what that's supposed to mean, and also that the simpson function always returns nan.
I know it's a lot of words and code, but does anybody know what's wrong?
To avoid the answer -4.5*Si(zoo)+ 8.--- just start the integration at a small positive number, e.g.:
x = sp.Symbol('x')
print sp.integrate( x * sin(3./x), (x, 0.000001, 2) )
and you'll get an answer like 1.0996940...
You can justify this because |s(x)| <= x for small x, so the interval [0, epsilon] can't contribute that much.
Btw - your simpson implemention seems to check out.