How to use inequalities in julia with SymPy?
no does works:
using SymPy
#syms x
ineq = (x+1)/(x-1) >=0
Related
I'm using symbolic math in Julia. When I do the differentiation it comes out very nicely, but I cant get the coefficients out
using SymPy
#vars x y
z = x*(10 + 5*x + 4*y)
dz = diff(z,x)
x_s = solveset(dz,x)
how do I get the the coefficients out of x_s?
You can use elements to get the elements of a finite sets as an array:
julia> elements(s)
1-element Array{Sym,1}:
-2*y/5 - 1
To get the coefficients can be done different ways, but here we convert the value to a Polynomial type, then use its coeffs method:
julia> p = sympy.Poly(elements(s)[1], y)
Poly(-2/5*y - 1, y, domain='QQ')
julia> p.coeffs()
2-element Array{Sym,1}:
-2/5
-1
As per my comment, the following works but isn't exactly what I'd describe as pretty:
julia> x_s.__pyobject__.args[1].__pyobject__.args[1]
-1
julia> x_s.__pyobject__.args[1].__pyobject__.args[2]
-2⋅y
─────
5
julia> x_s.__pyobject__.args[1].__pyobject__.args[2].__pyobject__.args[1]
-2/5
I couldn't find an accessor function in Sympy.jl that simplifies this, but as you say this could be the basis for rolling your own.
I'm trying to numerically solve a nonlinear system of equations in Julia. I'm using Newthon method. The only thing I don't know how to do, is to compute an Jacobian matrix. So far I couldn't find the function to compute partial derivatives.
My system:
f(x1, x2) = 2*x2^2+x1^2
g(x1, x2) = (x1-1)^2 + (x2-1/2)^2
Thanks for your support,
Best regards,
Szymon.
Let me write as an answer what I already mentioned in the comments. You could use automatic differentiation to calculate the partial derivatives:
julia> using ForwardDiff
julia> f(x) = 2*x[2]^2+x[1]^2 # f must take a vector as input
f (generic function with 2 methods)
julia> g = x -> ForwardDiff.gradient(f, x); # g is now a function representing the gradient of f
julia> g([1,2]) # evaluate the partial derivatives (gradient) at some point x
2-element Array{Int64,1}:
2
8
Base R provides a function D() that outputs the expression of the derivative of a given function.
For example:
f <- expression(x^3+2*x)
D(f, "x") # with respect to x
# 3 * x^2 + 2
Is there a similar function that would yield the expression of the integral of a function?
I know that stats::integrate() will evaluate the integral of a function for a given interval, but as far as I know, it will not output the expression of the Integral.
As mentioned in the comments, the package Ryacas can do indefinite integrals:
library(Ryacas)
x = Sym('x')
f = expression(x^3 + 2*x)
Integrate(f, x)
## expression(x^4/4 + x^2)
There is no base function for integration but for differentiation because differentiation is mechanics, integration is art.
This is an attempt to answer the following question: https://matheducators.stackexchange.com/questions/11757/small-data-sets-with-integral-sample-standard-deviations
So the intent of the following code is to find examples of small datasets with integer standard deviation. That can be formulated as a quadratically constrained mixed integer quadratic program, so I try to use Gurobin from Julia. Following is my code:
using JuMP
using Gurobi
m = Model(solver = GurobiSolver() )
#variable(m, 0<= x[1:20] <= 100, Int)
#variable(m, Gj, Int)
#constraint(m, Gj == sum(x[1:20])/20 )
#variable(m, Var, Int)
#constraint(m, Var == sum( (x[1:20]-Gj).^2/19) )
#variable(m, sd, Int)
#constraint(m, sd * sd == Var)
### We need some restrictions to avoid all equal, < or zero, solutions:
#constraint(m, sd >= 5)
#objective(m, Min, sd)
print(m)
status = solve(m)
println("Objective value: ", getobjectivevalue(m) )
x = getvalue(x)
Running this results in:
ERROR: Gurobi.GurobiError(10021, "Quadratic equality constraints")
Stacktrace:
[1] optimize(::Gurobi.Model) at /home/kjetil/.julia/v0.6/Gurobi/src/grb_solve.jl:7
[2] optimize!(::Gurobi.GurobiMathProgModel) at /home/kjetil/.julia/v0.6/Gurobi/src/GurobiSolverInterface.jl:294
[3] #solve#101(::Bool, ::Bool, ::Bool, ::Array{Any,1}, ::Function, ::JuMP.Model) at /home/kjetil/.julia/v0.6/JuMP/src/solvers.jl:173
[4] solve(::JuMP.Model) at /home/kjetil/.julia/v0.6/JuMP/src/solvers.jl:148
Any ideas?
A math programming solver like Gurobi Optimizer cannot solve models with quadratic equality constraints. Here are the types of constraints that Gurobi Optimizer can solve. To solve your model using Gurobi Optimizer, you must transform your constraints into one of these forms, such as quadratic inequality constraints.
The major problem is that, in general, a quadratic equality is not convex, and most solvers only work for convex problems (plus integer constraints). A product of two binary variables is easy to linearise (it's the equivalent of a logical AND), that of one binary variable and one continuous variable is easy too; the rest is not so easy.
Since Gurobi 9, you can solve nonconvex bilinear problems, in particular those having quadratic equality constraints. You just have to add the right parameter. With Gurobi.jl, if m is your JuMP model, you can do this:
set_optimizer_attribute(m, "NonConvex", 2)
All,
I've just been starting to play around with the Julia language and am enjoying it quite a bit. At the end of the 3rd tutorial there's an interesting problem: genericize the quadratic formula such that it solves for the roots of any n-order polynomial equation.
This struck me as (a) an interesting programming problem and (b) an interesting Julia problem. Has anyone out there solved this one? For reference, here is the Julia code with a couple toy examples. Again, the idea is to make this generic for any n-order polynomial.
Cheers,
Aaron
function derivative(f)
return function(x)
# pick a small value for h
h = x == 0 ? sqrt(eps(Float64)) : sqrt(eps(Float64)) * x
# floating point arithmetic gymnastics
xph = x + h
dx = xph - x
# evaluate f at x + h
f1 = f(xph)
# evaluate f at x
f0 = f(x)
# divide the difference by h
return (f1 - f0) / dx
end
end
function quadratic(f)
f1 = derivative(f)
c = f(0.0)
b = f1(0.0)
a = f(1.0) - b - c
return (-b + sqrt(b^2 - 4a*c + 0im))/2a, (-b - sqrt(b^2 - 4a*c + 0im))/2a
end
quadratic((x) -> x^2 - x - 2)
quadratic((x) -> x^2 + 2)
The package PolynomialRoots.jl provides the function roots() to find all (real and complex) roots of polynomials of any order. The only mandatory argument is the array with coefficients of the polynomial in ascending order.
For example, in order to find the roots of
6x^5 + 5x^4 + 3x^2 + 2x + 1
after loading the package (using PolynomialRoots) you can use
julia> roots([1, 2, 3, 4, 5, 6])
5-element Array{Complex{Float64},1}:
0.294195-0.668367im
-0.670332+2.77556e-17im
0.294195+0.668367im
-0.375695-0.570175im
-0.375695+0.570175im
The package is a Julia implementation of the root-finding algorithm described in this paper: http://arxiv.org/abs/1203.1034
PolynomialRoots.jl has also support for arbitrary precision calculation. This is useful for solving equation that cannot be solved in double precision. For example
julia> r = roots([94906268.375, -189812534, 94906265.625]);
julia> (r[1], r[2])
(1.0000000144879793 - 0.0im,1.0000000144879788 + 0.0im)
gives the wrong result for the polynomial, instead passing the input array in arbitrary precision forces arbitrary precision calculations that provide the right answer (see https://en.wikipedia.org/wiki/Loss_of_significance):
julia> r = roots([BigFloat(94906268.375), BigFloat(-189812534), BigFloat(94906265.625)]);
julia> (Float64(r[1]), Float64(r[2]))
(1.0000000289759583,1.0)
There are no algebraic formulae for a general polynomials of degree five and above (infact there cant be see here). So theoretically, you could proceed using the same methodology for solutions to cubics and quartics, but even that would be a lot of hard work given very unwieldy formulae for roots of quartics. You could also use a CAS like SymPy to find out those formulae.