Symbolics.jl icon indicating copy to clipboard operation
Symbolics.jl copied to clipboard

Substitute with `fold=true` does not preserve rationals

Open hersle opened this issue 1 year ago • 4 comments

It is annoying that

@variables x
substitute(1//2 * cos(x), x => 0)

gives 0.5 and not 1//2.

The reason is natural: cos(0) evaluates to 1.0 (not 1), giving (1//2) * 1.0, which is converted to 0.5. Is there a way to fix this?

hersle avatar Oct 07 '24 19:10 hersle

@shashi is this intended?

ChrisRackauckas avatar Oct 08 '24 11:10 ChrisRackauckas

well it's incidental like the OP said. Maybe fold could call a narrow_type function which turns floats into integers if is_integer is true.

shashi avatar Oct 25 '24 17:10 shashi

How about if SymbolicUtils.simplify() by default uses the rule

using SymbolicUtils
r = @rule (~x::SymbolicUtils._isinteger) => Int(~x)

Then

r(7.0) # outputs 7

If you think this would work, can you point me to where I should add it for it to work on nested expressions? Like

@syms x
r(7.0*x) # should output 7x

I am not familiar enough with Symbolics to know how it should be added.

hersle avatar Oct 29 '24 12:10 hersle

That's a nice idea. It would probably go in https://github.com/JuliaSymbolics/SymbolicUtils.jl/blob/master/src/simplify_rules.jl

ChrisRackauckas avatar Oct 29 '24 12:10 ChrisRackauckas