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.
Related
I need to solve a large number of small convex optimisation problems with the same constraints, so I am trying to use cvxpy's DPP feature to cache/speedup compilation. It doesn't seem to work for my problem containing a single complex matrix parameter L.
import numpy as np
import cvxpy as cp
A = np.eye(4)+np.eye(4)*1j
L = cp.Parameter((4,4),complex=True)
X = cp.Variable((4,4),hermitian=True)
obj = cp.Minimize(cp.norm(X-L,'fro'))
prob = cp.Problem(obj)
L.value = A
assert prob.is_dcp(dpp=True)
prob.solve(solver=cp.SCS,verbose=True)
If I change the definitions of A and L to A=np.eye(4) and L = cp.Parameter((4,4)), then I do see the (Subsequent compilations of this problem, using the same arguments, should take less time.) message in the verbose print out.
I am using cvxpy version 1.2.1.
Does anyone know what's going on? Many thanks!
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
If the price charged for a crayon is p cents, then x thousand crayons
will be sold in a certain school store, where p(x)= 122-x/34 .
Using Python, calculate how many crayons must be sold to maximize
revenue.
I can solve this by hand much easily, the only problem is how can I do it using plain Python? I am using IDLE (Python GUI). I am new to Python and haven't downloaded any external libraries. Any help will be greatly appreciated.
What I've done up to this point is
import math
def f(x):
return (122-(x/34.0))
def g(x):
return x*f(x)
def h(x):
return (122-(2*x/34.0))
Use SymPy. It's simple, beautiful and powerful.
You can write down your equations with simpify(), like that:
p = simpify('122 - x/34')
And define symbols for symbolic evaluation with Symbol() and symbols().
With that you can do things like simply use solve() function for any given equation. i.e. x + 4 = 2x:
res = solve('x + 4 - 2*x')
It's pretty much the tool I use for any math work with python.
So, you should go and download an external library for this, as it's not functionality that python makes easy to implement natively. Also, if you're serious about doing mathematical computation in python I would suggest switching operating systems to something like OSX or linux, simply because compiling old FORTRAN libraries (required for much performant mathematical computing) is a huge pain on Windows.
You have to make use of the scipy library here, which has an optimize module. Specifically I would suggest using the optimize.minimize_scalar function. Docs can be found here.
>>> from scipy.optimize import minimize_scalar
>>> def g(x):
... return -(x*(122 - (x/34))) # inverse because you're minimizing.
>>> minimize_scalar(g, bounds=(1, 10000), method='bounded')
status: 0
nfev: 6
success: True
fun: -126514.0
x: 2074.0
message: 'Solution found.'
I recently reinstalled my python environment and a code that used to work very quickly now creeps at best (usually just hangs taking up more and more memory).
The point at which the code hangs is:
solve(exp(-alpha * x**2) - 0.01, alpha)
I've been able to reproduce this problem with a fresh IPython 0.13.1 session:
In [1]: from sympy import solve, Symbol, exp
In [2]: x = 14.7296138519
In [3]: alpha = Symbol('alpha', real=True)
In [4]: solve(exp(-alpha * x**2) - 0.01, alpha)
this works for integers but also quite slow. In the original code I looped over this looking for hundreds of different alpha's for different values of x (other than 14.7296138519) and it didn't take more than a second.
any thoughts?
The rational=False flag was introduced for such cases as this.
>>> q=14.7296138519
>>> solve(exp(-alpha * q**2) - 0.01, alpha, rational=False)
[0.0212257459123917]
(The explanation is given in the issue cited above.)
Rolling back from version 0.7.2 to 0.7.1 solved this problem.
easy_install sympy==0.7.1
I've reported this as a bug to sympy's google code.
I am currently running sympy ver: 1.11.1
This is for all I know the latest version.
However, hanging as was described, when solving a set of 3 differential for 3 angular double differentials persist.
Eg.:
sols = solve([LE1, LE2, LE3], (the_dd, phi_dd, psi_dd),
simplify=False, rational=False)
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.