Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
```
25 changes: 25 additions & 0 deletions src/utils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -414,3 +414,28 @@ 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))
symbolic_to_float(x::Number) = 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
10 changes: 10 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,12 @@ using Symbolics
sorted_vars2 = Symbolics.get_variables(ex2; sort = true)
@test isequal(sorted_vars2, [x, y])
end

@testset "symbolic_to_float" begin
@variables x
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((big(1)//2)*√(279//4)) isa BigFloat
symbolic_to_float((-1//2)*√(279//4)) isa Float64
end