JuliaHomotopyContinuation / HomotopyContinuation.jl

A Julia package for solving systems of polynomials via homotopy continuation.

Home Page:https://www.JuliaHomotopyContinuation.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Convert Expression to Float64 or ComplexF64

alexheaton2 opened this issue · comments

If I make substitutions and obtain an Expression which has no variables remaining, I should be able to convert that Expression into a Float64 or ComplexF64. Example:
using HomotopyContinuation
f = Variable(:x,1,1) - Variable(:x,1,2)
bexp = subs(f, [Variable(:x,1,i)=>rand() for i in 1:2]...)
b = Float64(bexp)
However, this raises an error. I would use this frequently to produce the constant term of an affine linear subspace that I want to pass through a given, known point. Also, I am NOT sure if this is the correct Github thing to do... raising an issue, I mean. Please instruct me on proper conduct if needed. :)

I have recently found the to_number function, but since Expression is a child of Number, it does seem like Float64(b) should work.

Hi Alex,

this is the right place for asking such questions and with opening an issue you did the right thing.

One way to get what you want is the following:

F = System([f])
F(rand(2))

In the second line you need to take care of the ordering of the variables (in this example it is not needed, of course, but in others it may be). The command variables(F) lets you check this. It is also possible to give a manual ordering of variables.

Hi Alex,

thanks for the report. I added in #444 code that should make this work.
There are also a couple other ways to get your expression working which is maybe even more straightforward:

julia> using HomotopyContinuation

julia> f = Variable(:x,1,1) - Variable(:x,1,2)
x₁₋₁ - x₁₋₂

julia> X = rand(2)
2-element Array{Float64,1}:
 0.20507861126808313
 0.32288432730545225

julia> bexp = subs(f, [Variable(:x,1,i)=>X[i] for i in 1:2]...)
-0.117805716037369

julia> typeof(bexp)
Expression

julia> bexp = evaluate(f, [Variable(:x,1,i)=>X[i] for i in 1:2]...)
-0.11780571603736911

julia> typeof(bexp)
Float64

julia> bexp = f([Variable(:x,1,i)=>X[i] for i in 1:2]...)
-0.11780571603736911

julia> typeof(bexp)
Float64

julia> bexp = f(Variable.(:x,1,1:2)=>X)
-0.11780571603736911

julia> typeof(bexp)
Float64