How can I convert this equation to Python code
enter image description here
You can need to learn about operator precedence and associativity in Programming Languages. That way you can strengthen your understanding of how to perform complex calculations in Python.
Apart from that try to break the problem into smaller subproblems and combine the smaller subproblems to generate solution for the larger problem.
[0.38C(1-g/C)2] = (0.38 * C) * (1 - (g/C) * 2)
[1-(g/C)(X)] = (1 - (g/C) * X)
173X2 = 173 * 2
[(X-1)+[(X-1)2 + (16X/C)]1/2] = ((X-1)+((X-1)*2 + (16*X/C))* 1/2)
Now put all values in the equation:
"d=[0.38C(1-g/C)2]/[1-(g/C)(X)]+173X2[(X-1)+[(X-1)2 + (16X/C)]1/2]"
d = (((0.38 * C)*(1 - (g/c)) * 2 ) / (1 - (g/C) * X)) + 172 * 2 *((X-1) +((X-1)+((X-1)*2 + (16*X/C))* 1/2)
Related
I am trying to use plotly to graph a huge function which is in turn a sum of other functions - I want to append the smaller functions to arrays and add them up to the final function. Process with simple functions works, e.g.:
import numpy as np
import plotly.graph_objects as go
pi = math.pi
X, Y, Z = np.mgrid[-2:2:100j, -2:2:100j, -2:2:100j]
x=[pi*2,4]
values1 = pi*X*X+Y*Y
values2 = Z*Z
values.append(values1*x[0])
values.append(values2*x[1])
valuestot=values[0]+values[1]
fig = go.Figure(data=go.Isosurface(
x=X.flatten(),
y=Y.flatten(),
z=Z.flatten(),
value=valuestot.flatten(),
isomin=-0.1,
isomax=0.1
))
fig.show()
However, problem occurs when I use a longer function (respective to values1), for example:
n1s2 = nns21 * (((3 * nas21 / pi) ** (1 / 4)) * math.exp( -nas21 * ((X + cXN1) ** 3 + (Y + cYN1) ** 2 + (Z + cZN1) ** 2))) + nns22 * ( ((2 * nas22 / pi) ** (1 / 4)) * math.exp( -nas22 * ((X + cXN1) ** 2 + (Y + cYN1) ** 3 + (Z + cZN1) ** 2)))
gives the TypeError: only size-1 arrays can be converted to Python scalars error for the line of the function in the code.
I tried all the solutions with np.vectorize() given on different forums, yet that does not help, as python presumably reads the long line as a list of items. How could I make the line read as a single function which is recognized by python? Thank you for your help.
Succeeded - got a suggestion from a brilliant CS student to change math.exp() to np.exp() so that different exponents account for separate mgrid vectors (X,Y,Z).
I'm new to numpy, and trying to implement the following equation.
The equation has two parts, and should give a final value called Sigma.
the equation is taken from the paper as below image:
image of the equation to provide the result of Sigma
I tried to implement it as below, but when running the code, the value c is giving nan
c = np.sqrt(np.log(2 / np.sqrt( 16 * delta + 1 ) -1 ))
sigma = (c + np.sqrt(np.square(c) + epsilon) ) * s / (epsilon * np.sqrt(2))
appreciate if you can advise on how to implement it in numpy
You missed a bracket in your code
c = np.sqrt(np.log(2 / (np.sqrt( 16 * delta + 1 ) -1 )))
sigma = (c + np.sqrt(np.square(c) + epsilon) ) * s / (epsilon * np.sqrt(2))
To get a valid c value, you should input delta like 0 < delta < 0.5.
You are missing a parenthesis. This is the correct formula:
c = np.sqrt(np.log(2/(np.sqrt(16*delta + 1) -1)))
Also, keep in mind that (as the paper states) this is defined only for .
This question already has an answer here:
How to convert quadratic to linear program?
(1 answer)
Closed 7 years ago.
I'm in need of an LP where you can multiply two non-constants. Here is the following code that I am trying to perform:
import cvxpy as cvx
a = cvx.Variable()
b = cvx.Variable()
c = cvx.Variable()
obj = cvx.Maximize(((0.4270437386 * a) + (0.1737677971 * b) + (0.21763175116 * c) - 0.03) / (((((2 * a * 0.424718270) * b) * (0.195770376 ** 0.5)) * (0.022090814 ** 0.5)) * ((2 * c * -0.041137487) * b * (0.194241184 ** 0.5) * (0.022090814 ** 0.5)) * (2 * a * 0.363033596 * c * (0.195770376** 0.5) * (0.194241184 ** 0.5))))
Unfortunately this raises an error:
cvxpy.error.DCPError: Cannot multiply two non-constants.
This stems from several areas in the denominator of obj, such as (2 * a * 0.424718270) * b).
I was wondering if anyone knew of any LP programs where we can do this sort of thing? Is it even possible.
The issue is that you are asking a linear programming package to optimize for a non-linear objective function. This is much more than a technical issue. The methods used to solve linear programming problems do not make sense and cannot be tweaked.
I am using Python 2 and the fairly simple method given in Wikipedia's article "Cubic function". This could also be a problem with the cube root function I have to define in order to create the function mentioned in the title.
# Cube root and cubic equation solver
#
# Copyright (c) 2013 user2330618
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://www.mozilla.org/MPL/2.0/.
from __future__ import division
import cmath
from cmath import log, sqrt
def cbrt(x):
"""Computes the cube root of a number."""
if x.imag != 0:
return cmath.exp(log(x) / 3)
else:
if x < 0:
d = (-x) ** (1 / 3)
return -d
elif x >= 0:
return x ** (1 / 3)
def cubic(a, b, c, d):
"""Returns the real roots to cubic equations in expanded form."""
# Define the discriminants
D = (18 * a * b * c * d) - (4 * (b ** 3) * d) + ((b ** 2) * (c ** 2)) - \
(4 * a * (c ** 3)) - (27 * (a ** 2) * d ** 2)
D0 = (b ** 2) - (3 * a * c)
i = 1j # Because I prefer i over j
# Test for some special cases
if D == 0 and D0 == 0:
return -(b / (3 * a))
elif D == 0 and D0 != 0:
return [((b * c) - (9 * a * d)) / (-2 * D0), ((b ** 3) - (4 * a * b * c)
+ (9 * (a ** 2) * d)) / (-a * D0)]
else:
D1 = (2 * (b ** 3)) - (9 * a * b * c) + (27 * (a ** 2) * d)
# More special cases
if D != 0 and D0 == 0 and D1 < 0:
C = cbrt((D1 - sqrt((D1 ** 2) - (4 * (D0 ** 3)))) / 2)
else:
C = cbrt((D1 + sqrt((D1 ** 2) - (4 * (D0 ** 3)))) / 2)
u_2 = (-1 + (i * sqrt(3))) / 2
u_3 = (-1 - (i * sqrt(3))) / 2
x_1 = (-(b + C + (D0 / C))) / (3 * a)
x_2 = (-(b + (u_2 * C) + (D0 / (u_2 * C)))) / (3 * a)
x_3 = (-(b + (u_3 * C) + (D0 / (u_3 * C)))) / (3 * a)
if D > 0:
return [x_1, x_2, x_3]
else:
return x_1
I've found that this function is capable of solving some simple cubic equations:
print cubic(1, 3, 3, 1)
-1.0
And a while ago I had gotten it to a point where it could solve equations with two roots. I've just done a rewrite and now it's gone haywire. For example, these coefficients are the expanded form of (2x - 4)(x + 4)(x + 2) and it should return [4.0, -4.0, -2.0] or something similar:
print cubic(2, 8, -8, -32)
[(-4+1.4802973661668753e-16j), (2+2.9605947323337506e-16j), (-2.0000000000000004-1.1842378929335002e-15j)]
Is this more a mathematical or a programming mistake I'm making?
Update: Thank you, everyone, for your answers, but there are more problems with this function than I've iterated so far. For example, I often get an error relating to the cube root function:
print cubic(1, 2, 3, 4) # Correct solution: about -1.65
...
if x > 0:
TypeError: no ordering relation is defined for complex numbers
print cubic(1, -3, -3, -1) # Correct solution: about 3.8473
if x > 0:
TypeError: no ordering relation is defined for complex numbers
Wolfram Alpha confirms that the roots to your last cubic are indeed
(-4, -2, 2)
and not as you say
... it should return [4.0, -4.0, -2.0]
Not withstanding that (I presume) typo, your program gives
[(-4+1.4802973661668753e-16j), (2+2.9605947323337506e-16j), (-2.0000000000000004-1.1842378929335002e-15j)]
Which to accuracy of 10**(-15) are the exact same roots as the correct solution. The tiny imaginary part is probably due, as others have said, to rounding.
Note that you'll have to use exact arithmetic to always correctly cancel if you are using a solution like Cardano's. This one of the reasons why programs like MAPLE or Mathematica exist, there is often a disconnect from the formula to the implementation.
To get only the real portion of a number in pure python you call .real. Example:
a = 3.0+4.0j
print a.real
>> 3.0
Hooked's answer is the way to go if you want to do this numerically. You can also do it symbolically using sympy:
>>> from sympy import roots
>>> roots('2*x**3 + 8*x**2 - 8*x - 32')
{2: 1, -4: 1, -2: 1}
This gives you the roots and their multiplicity.
You are using integer values - which are not automatically converted to floats by Python.
The more generic solution will be to write coefficients in the function as float numbers - 18.0 instead of 18, etc. That will do the trick
An illustration - from the code:
>>> 2**(1/3)
1
>>> 2**(1/3.)
1.2599210498948732
>>>
I have the following set of equations, and I want to solve them simultaneously for X and Y. I've been advised that I could use numpy to solve these as a system of linear equations. Is that the best option, or is there a better way?
a = (((f * X) + (f2 * X3 )) / (1 + (f * X) + (f2 * X3 ))) * i
b = ((f2 * X3 ) / (1 + (f * X) + (f2 * X3))) * i
c = ((f * X) / (1 + (j * X) + (k * Y))) * i
d = ((k * Y) / (1 + (j * X) + (k * Y))) * i
f = 0.0001
i = 0.001
j = 0.0001
k = 0.001
e = 0 = X + a + b + c
g = 0.0001 = Y + d
h = i - a
As noted by Joe, this is actually a system of nonlinear equations. You are going to need more firepower than numpy alone provides.
Solution of nonlinear equations is tricky, and the typical approach is to define an objective function
F(z) = sum( e[n]^2, n=1...13 )
where z is a vector containing a value for each of your 13 variables a,b,c,d,e,f,g,h,i,X,Y and e[n] is the amount by which each of your 13 equations is violated. For example
e[3] = (d - ((k * Y) / (1 + (j * X) + (k * Y))) * i )
Once you have that objective function, then you can apply a nonlinear solver to try to find a z for which F(z)=0. That of course corresponds to a solution to your equations.
Commonly used solvers include:
The Solver in Microsoft Excel
The python library scipy.optimize
Fitting routines in the Gnu Scientific Library
Matlab's optimization toolbox
Note that all of them will work far better if you first alter your set of equations to eliminate as many variables as practical before trying to run the solver (e.g. by substituting for k wherever it is found). The reduced dimensionality makes a big difference.