JuliaSymbolics / SymbolicUtils.jl

Symbolic expressions, rewriting and simplification
https://docs.sciml.ai/SymbolicUtils/stable/
Other
524 stars 99 forks source link

Is there a function for knowing whether an expression is a polynomial? #476

Open qwertyjl opened 1 year ago

qwertyjl commented 1 year ago

Is there a function for knowing whether an expression is a polynomial? A function that can be used in the rules as well would be useful: ~x::is_polynomial

bowenszhu commented 1 year ago

polynomial_coeffs in Symbolics.jl https://github.com/JuliaSymbolics/Symbolics.jl/blob/e45badffda9bf5e4ba8e76914c171a73a08346c1/src/semipoly.jl#L282 Many examples can be found in https://github.com/JuliaSymbolics/Symbolics.jl/blob/e45badffda9bf5e4ba8e76914c171a73a08346c1/test/semipoly.jl

You can check if the residual it returns is zero. For example,

using Symbolics
@variables x y
expr = x + sin(x) + 1 + y
dict, residual = polynomial_coeffs(expr, [x])
@show dict # Dict{Any, Any}(x => 1, 1 => 1 + y)
@show residual # sin(x)
isequal(residual, 0) # false

The functions defined in https://github.com/JuliaSymbolics/Symbolics.jl/blob/e45badffda9bf5e4ba8e76914c171a73a08346c1/src/semipoly.jl are not added to the documentation and may be changed afterwards (I'm not completely sure).

qwertyjl commented 1 year ago

Checking whether the residual is 0 is not enough. I asked on discourse and they recommended this one:

function is_poly(expr, vars)
       p,r = polynomial_coeffs(expr, vars)
       length(intersect(Symbolics.get_variables(r), vars)) == 0   # isempty(Symbolics.get_variables(r) ∩ vars)
end
bowenszhu commented 1 year ago

Checking whether the residual is 0 is not enough.

Do you have a test case?

qwertyjl commented 1 year ago

For example x^2+3x+5+sin(a)+f(a, b) Is a polynomial if a and b are considered constant. It is necessary to ask with respect to which variables you want to check whether an expression is a polynomial