Solving implicit equation in python using f solve - python

I want to write a program to ask for the values of Q,y,b,x,S0 then find the value of n from the following image
I used f solve to write this code:
from scipy.optimize import fsolve
def f(n,Q=float(input("Q=")),y=float(input("y=")),b=float(input("b=")),x=float(input("x=")),S_0=float(input("S0="))):
return (1/n)*((y*(b+x*y))**(5/3))/((b+2*y*(1+x**2)**(1/2))**(2/3))*S_0-Q
a=fsolve(f,1)
print(a)
print(f(a))
But it gives a false result as output for my inputs here:
Q=21
y=7.645
b=2
x=1
S0=0.002
/usr/lib/python3/dist-packages/scipy/optimize/minpack.py:236: RuntimeWarning: The iteration is not making good progress, as measured by the
improvement from the last ten iterations.
warnings.warn(msg, RuntimeWarning)
[ 1.]
[-20.68503025]
I wrote this in Online Python. I don't know what is the meaning of this error. also the output is wrong. answer should be n=0.015 for this specific input. how can I fix this code?

I rearranged your equation, and this somehow gets your expected result. I'm really not quite sure what is the issue, sorry!
return (S_0/Q)*((y*(b+x*y))**(5/3)/(b+2*y*(1+x**2)**(1/2))**(2/3))-n

Related

The largevalue on fipy internal boundary condition

I have tried internal boundary condition in code below.
I found that while I have not set an external boundary condition, the solved result will depend on the LargeValue. Besides, while I increase the largeValue, I must redefine the equation again, otherwise the equation couldn't be changed by just setting a new value to LargeValue.
I have used the sweep method to try to get a better result, but it does not work.
Below is my code. Is there any mistake? Hope someone will help me!
for step in range(steps):
equation2=DiffusionTerm(coeff=perittivity)==ImplicitSourceTerm(largeValue*mask)-largeValue*mask*value
potential.setValue(0)
k=0.5
residual=1
while residual>1e-10 and abs(k-residual)>1e-18 :
k=residual
residual=equation2.sweep(potential)
if __name__=="__main__":
viewer.plot()
print step,residual,k-residual#,equation2,largeValue
largeValue=Variable(value = largeValue.value*1.1)

Function definition and function call produce syntax error in python 3, even when copied and pasted

I am trying to solve the problem of a least squares fit of a power law spliced to a third order polynomial in python using gradient descent. I have computed gradients with respect to the parameters in Matlab. The boundary conditions I computed by hand. I am running into a syntax error in my chi-squared minimization algorithm, which must take into account the boundary conditions. I am doing this for a machine learning class in which I am completing a somewhat self-directed and self-proposed long term project, but I am stuck because of this syntax error that I am not sure how to overcome. I will not get class credit for this. It is simply something to put on my resume.
def polypowerderiv(x,a1,b1,c1,a2,b2,c2,d2,boundaryx,ydat):
#need to minimize square of ydat-polypower
#from Mathematica, to be careful
gradd2=2*(d2+c2*x+b2*x**2+a2*x**3-ydat)
gradc2=gradd2*x
gradb2=gradc2*x
grada2=gradb2*x
#again from Mathematica, to be careful
gradc1=2(c+a1*x**b1-ydat)
grada1=gradc1*x**b1
gradb1=grada1*a1*log(x)
return [np.sum(grada1),np.sum(gradb1),\
np.sum(gradc1),np.sum(grada2),np.sum(gradb2),\
np.sum(gradc2),np.sum(gradd2)]
def manualleastabsolutedifference(xdat, ydat, params,seed, maxiter, learningrate):
chisq=0 #chisq is the L2 error of the fit relative to the ydata
dof=len(xdat)-len(params)
xparams=seed
for step in np.arange(maxiter):
a1,b1,c1,a2,b2,c2,d2=params
chisq=polypowerlaw(xdat,params)
for i in np.arange(len(xdat)):
grad=np.zeros(len(seed))
for i in np.arange(seed):
polypowerlawboundarysolver=\
polypowerboundaryconstraint(xdat,a1,b1,c1,a2,b2,c2)
boundaryx=minimize(polypowerlawboundarysolver,x0=1000)
#hard coded to be half of len(xdat)
chisq+=abs(ydat-\
polypower(xdat,a1,b1,c1,a2,b2,c2,d2,boundaryx)
grad=\
polypowerderiv(xdat,a1,b1,c1,\
a2,b2,c2,d2,boundaryx,ydat)
params+=learningrate*grad
return params
The error I get is:
File "", line 14
grad=polypowerderiv(xdat,a1,b1,c1,a2,b2,c2,d2,boundaryx,ydat)
^
SyntaxError: invalid syntax
Also, I'm having some small trouble with formatting. Please help. This one of my first few posts to Stack Overflow ever, after many years of up and down votes. Thank you for your extensive help, community.
As per Alan-Fey, you forgot a closing bracket:
chisq+=abs(ydat-\
polypower(xdat,a1,b1,c1,a2,b2,c2,d2,boundaryx)
should be
chisq+=abs(ydat-\
polypower(xdat,a1,b1,c1,a2,b2,c2,d2,boundaryx))

RuntimeWarning: overflow encountered in exp in computing the logistic function

I'm getting this error when I try to compute the logistic function for a data mining method I'm implementing:
RuntimeWarning: overflow encountered in exp
My code:
def logistic_function(x):
# x = np.float64(x)
return 1.0 / (1.0 + np.exp(-x))
If I understood correctly from some related questions that the problem is that np.exp() is returning a huge value. I saw suggestions to let numpy ignore the warnings, but the problem is that when I get this error, then the results of my method are horrible. However when I don't get it, then they are as expected. So making numpy ignoring the warning is not a solution for me at all. I don't know what is wrong or how to deal with.
I don't even know if this is a result of a bug because sometimes I get this error and sometimes not! I went through my code many times and everything looks correct!
You should compute the logistic function using either scipy.special.expit, which in recent enough SciPy is more stable than your solution (although earlier versions got it wrong), or by reducing it to tanh:
def logistic_function(x):
return .5 * (1 + np.tanh(.5 * x))
This version of the function is stable, fast, and fairly accurate.

No solutions with exponents in python sympy

When I run this program, I get no solution at the end, but there should be a solution ( I believe). Any idea what I am doing wrong? If you take away the Q from e2 equation it seems to work correctly.
#!/usr/bin/python
from sympy import *
a,b,w,r = symbols('a b w r',real=True,positive=True)
L,K,Q = symbols('L K Q',real=True,positive=True)
e1=K
e2=(K*Q/2)**(a)
print solve(e1-e2,K)
It works if we do the following:
Set Q=1 or,
Change e2 to e2=(K*a)(Q/2)**(a)
I would still like it to work in the original way though, as my equations are more complicated than this.
This is just a deficiency of solve. solve is based mostly on heuristics, so sometimes it isn't able to figure out how to solve an equation when it's given in a particular form. The workaround here is to just call expand_power_base on the expression, since SymPy is able to solve K - K**a*(Q/2)**a:
In [8]: print(solve(expand_power_base(e1-e2),K))
[(2/Q)**(a/(a - 1))]
It's also worth pointing out that the result of [] from solve does not in any way mean that there are no solutions, only that solve was unable to find any. See the first note at http://docs.sympy.org/latest/tutorial/solvers.html.

Explain this algorithm

while solving the Palindrome problem on codechef I wrote an algorithm, which gave a TLE on test cases more than 10^6. So taking lead from people who had already solved it I wrote the following code in python.
################################################
### http://www.codechef.com/problems/TAPALIN ###
################################################
def pow(b,e,m):
r=1
while e>0:
if e%2==1:
r=(r*b)%m
e=e>>1
b=(b*b)%m
return r
def cal(n,m):
from math import ceil
c=280000002
a=pow(26, int(ceil(n/2)), m)
if(n%2==0):
return ((52*(a-1+m)%m)*c)%m
else:
return ((52*(((a-1+m)*c)%m))%m+(a*26)%m)%m
c=int(raw_input())
m=1000000007
for z in range(c):
print cal(int(raw_input()),m)
the pow function is the Right-to-left binary method. what i do not understand is:
where did the value 280000002 came from?
why do we need to perform so many mod operations?
is this some famous algorithm of which I am unaware about?
Almost every submitted code on codechef makes use of this very algorithm, but I am unable to decipher it's working. any link to the theory would be appreciated.
I am still unable to figure out what is happening in this exactly. can anyone write a pseudocode for this formula/algo? also help me understand time complexity for this code. another thing that amazes me is, if I write this code as:
################################################
### http://www.codechef.com/problems/TAPALIN ###
################################################
def modular_pow(base, exponent):
result=1
while exponent > 0:
if (exponent%2==1):
result=(result * base)%1000000007
exponent=exponent >> 1
base=(base*base)%1000000007
return result
c=int(raw_input())
from math import ceil
for z in range(c):
n=int(raw_input())
ans=modular_pow(26, int(ceil(n/2)))
if(n%2==0):
print ((52*((ans)-1+ 1000000007)%1000000007)*280000002)%1000000007
else:
print ((52*((((ans)-1+ 1000000007)*280000002)%1000000007))%1000000007+(ans*26)%1000000007)%1000000007
this improves the performance from 0.6secs to 0.4 secs. though the best code runs in 0.0 seconds. I am so much confused.
The number 280000002 is Modular Multiplicative Inverse of 25 mod 10^9 + 7, because we know 10^9 + 7 is prime so it's simply calculated using pow(25, 10^9 + 7 - 2, 10^9 + 7). Read more here: http://en.wikipedia.org/wiki/Modular_multiplicative_inverse
And we need to perform so many mod operations because we don't want to work with big numbers ;-)
Never seen this algorithm before but walking through it with some of the easier test cases starts to reveal what is happening (BTW, my guess is everyone is using it because it was the top answer on code chef and everyone is just copying it, I don't think you have to assume it's the only way to do it).
To answer your questions:
where did the value 280000002 came from?
280000002 is the modulo multiplicative inverse of 25 mod 1000000007. This means that the following congruence is true
280000002 * 25 === 1 (mod 1000000007)
why do we need to perform so many mod operations?
Probably just to not be dealing with huge numbers along the way. Although there is some extra math in there that seems to me to just be making the numbers bigger than they need to be, see my note at the end about that. Theoretically you could just do one big mod at the end and get the same result but it's possible our tiny CPUs don't like that.
is this some famous algorithm of which I am unaware about?
Again, I doubt it. This isn't really an algorithm as it is a mashed up math formula.
Speaking of math, there is some stuff in there that is questionable to me. It's been a while since I messed with this stuff but I'm pretty sure that (52*(a-1+m)%m) will always be equivalent to (52*(a-1)%m since 52m mod m = 0. Not sure why you would be adding that huge number there, you may see some performance gain if you get rid of that.

Categories