Skip to content

Commit

Permalink
Add symbolics_to_float converter
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisRackauckas committed Aug 27, 2024
1 parent b9d68b7 commit e49f153
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 1 deletion.
2 changes: 1 addition & 1 deletion docs/src/manual/expression_manipulation.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ Other additional manipulation functions are given below.
Symbolics.get_variables
Symbolics.tosymbol
Symbolics.diff2term
Symbolics.solve_for
Symbolics.degree
Symbolics.coeff
Symbolics.replace
Symbolics.occursin
Symbolics.filterchildren
Symbolics.fixpoint_sub
Symbolics.fast_substitute
Symbolics.symbolic_to_float
```
24 changes: 24 additions & 0 deletions src/utils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -414,3 +414,27 @@ symbolic expressions mapping variables w.r.t pvar2sym
function poly_to_symbol(polys, pvar2sym, sym2term, ::Type{T}) where {T}
map(f -> PolyForm{T}(f, pvar2sym, sym2term), polys)
end

"""
symbolic_to_float(x::Union{Num, BasicSymbolic})::Union{AbstractFloat, BasicSymbolic}
If the symbolic value is exactly equal to a number, converts the symbolic value
to a floating point number. Otherwise retains the symbolic value.
## Examples
```julia
symbolic_to_float((1//2 * x)/x) # 0.5
symbolic_to_float((1/2 * x)/x) # 0.5
symbolic_to_float((1//2)*√(279//4)) # 4.175823272122517
```
"""
function symbolic_to_float end
symbolic_to_float(x::Num) = symbolic_to_float(unwrap(x))
function symbolic_to_float(x::SymbolicUtils.BasicSymbolic)
if _x isa Number
return _x
else
substitute(x,Dict())
end
end
1 change: 1 addition & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ if GROUP == "All" || GROUP == "Core"
@safetestset "Semi-polynomial" begin include("semipoly.jl") end
@safetestset "Fuzz Arrays" begin include("fuzz-arrays.jl") end
@safetestset "Differentiation Test" begin include("diff.jl") end
@safetestset "Utils Test" begin include("utils.jl") end
@safetestset "ADTypes Test" begin include("adtypes.jl") end
@safetestset "Difference Test" begin include("difference.jl") end
@safetestset "Degree Test" begin include("degree.jl") end
Expand Down
6 changes: 6 additions & 0 deletions test/utils.jl
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Symbolics
using Symbolics: symbolic_to_float

@testset "get_variables" begin
@variables t x y z(t)
Expand All @@ -19,3 +20,8 @@ using Symbolics
sorted_vars2 = Symbolics.get_variables(ex2; sort = true)
@test isequal(sorted_vars2, [x, y])
end

symbolic_to_float((1//2 * x)/x) isa Float64
symbolic_to_float((1/2 * x)/x) isa Float64
symbolic_to_float((1//2)*√(279//4)) isa Float64
symbolic_to_float((-1//2)*√(279//4)) isa Float64

0 comments on commit e49f153

Please sign in to comment.