Why is this code outputting the wrong answer? - python

I'm new to both StackOverflow and coding so I appreciate any and all support!
I'm trying to solve for x in this equation: x = (p^4).((15-(4p))-((10(p^2))/(1-((2p).(1-p)))))
I wrote the below Python code in PyCharm in order to calculate 'x'.
When p=60, the output I expect is 0.735729231 but the output I get when I run the code is [-2981888998.72899]
I'd appreciate some guidance on what I'd need to change in order to output the expected value.
Many thanks!
PS: for reference: here is an image showing the equation written in its original format
import numpy as np
from sympy import *
p = 60
x = symbols('x')
eqn = Eq(x,(p**4)*((15-(4*p))-((10*(p**2))/(1-((2*p)*(1-p))))))
sol = solve(eqn,x)
print(sol)

I think there something wrong with your calculation or your equation.
You can do this directly without any packages,
p = 60
print((p**4)*((15-(4*p))-((10*(p**2))/(1-((2*p)*(1-p))))))
You don't need sympy to solve this because all the p variables are on the right side already. x is basically just your answer for subbing in p = 60 and expanding and solving the equation.
And You get the same number -2981888998.72899

Related

Solving equation using sympy

Given U(x) = ((x^2-1)^2- x^2) / ( x*(x^2-1)) , I'm trying to solve this equation :
U(x)- 1/U(x) = x using sympy and this is my code :
from sympy import *
x=symbols('x')
P,Q=x**2-1,x
t=(P**2-Q**2)/(P*Q)
print(solve(Eq(t-1/t,x),x))
I got a very long list (squeezed text with 1394 lines ) which is wrong comparing to the right solution i have got on wolfram alpha ( this is the right list : l3=[-0.507713305942872,0.507713305942872,-0.777861913430206,0.777861913430206,-1.46190220008154,1.46190220008154]
How can i get the same result in python using sympy ?
If you consider the numeric solutions
[-0.507713305942872,0.507713305942872,-0.777861913430206,0.777861913430206,-1.46190220008154,1.46190220008154]
to be correct, solve is probably not the right tool to use. These solutions are not actually "correct" they are just very very close. solve is trying to find an analytic i.e. 100% perfect solution. If you are fine with a little error you should use nsolve (numeric solve) instead of solve.
Also it seems you have an error in your equation code. I let sympy nsolve them, got a solution that wasn't among the WA ones. So I rewrote the equation and got nsolve to give me one of WA's solutions:
from sympy import *
x=symbols('x')
U = ((x**2-1)**2- x**2) / (x*(x**2-1))
eqn = U - 1/U - x
nsolve(eqn,x,0.1)
This yields 0.507713305942872. Which is the closest solution to the start value of 0.1.
As Oscar Benjamin has pointed out in the comments you can get all numeric solutions with
from sympy import *
x=symbols('x')
U = ((x**2-1)**2- x**2) / (x*(x**2-1))
eqn = U - 1/U - x
Poly(eqn.as_numer_denom()[0]).nroots()
By default nroots calculates 50 decimal places but you can specify how many you want by giving a keyword argument like so .nroots(n=decimal_places)

Python- Calculate this equation / expression

I have tried two different syntax's and when I ran the syntax's I got the mathmatical resolution in both attempts, but my quiz is wanting a specific line of code to get the result. Any idea how I'm S U P P O S E D to get python to calculate this?
This is not really a python problem and more a maths order of operations problem.
In both examples you provide, you are adding the 1 after you divide (5**(1/2)/2).
You want this:
ratio = (1 + 5**(1/2)) / 2
You should try this one. It will help you understand the operator order better.
(1+(5**(0.5)))/2
Hope this helps

How to return a finite (float) value with nonlinsolve in SymPy?

I am very new to programming, and had to use sympy for a school project.
I think I get that using nonlinsolve to return an angle gives an ImageSet with the angle + 2n*pi. However I want it to return only the value of the angle (in the interval [0,pi/2]), and as one value and not an interval.
from sympy import nonlinsolve, symbols,cos
x=symbols('x')
print(nonlinsolve([cos(x)-1],[x]).args[0][0])
I want the result to be 0 and not 2*n*pi.
Clarification : I know that the result is correct, but I only want one value, that I can use algebraically, and I don't know how Sympy works (how to manipulate ImageSets)
So I might be wrong because i dont use sympy, but the solution that solvers return seems to be corect to me.
ImageSet(Lambda(_n, 2*_n*pi), Integers)
From what I understand solver returned lambda function. Cosinus is a cyclic function which means it reapeats it's value every 2PI. So the solver says first solution (_n = 0) is 0, second (_n = 1) is 2pi and so on.
look at the function plot and it will hopefully make sense:
Wolfram Alpha - (cos(x) - 1)
EDIT: I think you need to use intersect method of imageset like this( note that intersect returns all the intersections, here i selected just the first one):
from sympy import nonlinsolve, symbols,cos, Interval
import math
x = symbols('x')
f = nonlinsolve([cos(x)-1], [x]).args[0][0]
sol = f.intersect(Interval(0, math.pi/2)).args[0]
print(sol)

Returning incorrect values with complex numbers in Python

I'm working a physics problem with complex numbers and think I'm setting everything up correctly but am obviously not doing something right along the way. It could be that I'm either not using the right equations or that I'm unfamiliar with how Python's handling the math, and I'm pretty sure I'm using the right stuff. I've already worked a problem using the same kind of procedure and got the correct value, so substituting my new values should
Given f = 1000, SWR = -5.9, L = 0.081, I apparently should be getting z = 1.4 - 0.23j.
Here's what I'm doing:
import numpy as np
import cmath
f = 1000 #frequency
SWR = -5.9
L = 0.081
w = 2*f*np.pi #angular frequency
c = 343 #speed of sound in air
k = w/c #wavenumber
BA = (SWR-1)/(SWR+1) #given
theta = 2*k*L-np.pi #given
z = (1+BA*np.e**(1j*theta))/(1-BA*np.e**(1j*theta)) #given
print(z)
This gives me z = (-4.699946746470462-2.3316919882323677j), obviously not what I'm being told is the correct value.
I've gone over this multiple times now and can't find anything wrong. I just again worked through the problem I already got correct and made the minor substitutions to fit these given values, and I'm still getting the returned value of z. I don't want to tell my professor his "check that your code is giving the correct results" result is wrong, but...
Am I missing something?
E: Apologies for the rough display, but I'm not sure I can type in LaTeX here. The following are what I'm working with. Furthermore, the final image shows that I worked basically the same problem correctly and that I should be able to just make some substitutions to work this one. Also note that in my code, z is actually z divided by the rhocS quantity. I'm after that, don't need to know their values.
Equation for z, BA, theta, and the worked similar problem

How to calculate factorial in Theano

Here is a simple example.
import theano
v = theano.tensor.scalar("variable")
factorial = ?
# Calculate factorial of v , like numpy.math.factorial(v), but it didn't work,
# Actually it should be a integer as a parameter of numpy.math.factorial function
result = theano.function([v], factorial)
There is few useful information on Internet. Something I found like
http://matthewrocklin.com/blog//work/2013/08/14/SymPy-Theano-part-4
which told me it belonged to "the future work", which means there is no solution for this problem.
How could that possible? I mean is there no body need calculate factorial in your theano project?
I had this problem when I designed a RBM with Poisson conditional possibility which needs calculate factorial of visible units in the energy function.
I have found the answer that we use gamma function to solve the factorial problem.
:( Sorry for bothering everybody!
Here is the detail:
https://groups.google.com/forum/#!msg/theano-users/ytqep8AickA/cE7QeJZxXzUJ
So here should be:
import theano
v = theano.tensor.scalar("variable")
factorial = theano.tensor.gamma(v)
# Calculate factorial of v , like numpy.math.factorial(v), but it didn't work,
# Actually it should be a integer as a parameter of numpy.math.factorial function
result = theano.function([v], factorial)
def factorial(x):
y = x-1
temp = x*y
it = y-1
for i in range(it):
y -= 1
temp = temp*y
print temp
Here is the edited solution without the Boolean operators. I know you found another answer but this may be helpful to you as well as others in the future.

Categories