Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lazy evaluation of rational powers #641

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
30 changes: 25 additions & 5 deletions src/types.jl
Original file line number Diff line number Diff line change
Expand Up @@ -608,9 +608,17 @@ function basicsymbolic(f, args, stype, metadata)
end
res
elseif f == (^) && length(args) == 2
res = args[1] ^ args[2]
if ispow(res)
@set! res.metadata = metadata
if args[2] isa Rational && !(args[1] isa Symbolic)
if !isinteger(args[2])
@goto FALLBACK
end
integer_type = only(typeof(args[2]).parameters)
res = args[1] ^ convert(integer_type, args[2])
mxhbl marked this conversation as resolved.
Show resolved Hide resolved
else
res = args[1] ^ args[2]
if ispow(res)
@set! res.metadata = metadata
end
end
mxhbl marked this conversation as resolved.
Show resolved Hide resolved
res
else
Expand Down Expand Up @@ -1210,9 +1218,21 @@ function ^(a::SN, b)
elseif b isa Number && b < 0
Div(1, a ^ (-b))
elseif ismul(a) && b isa Number
coeff = unstable_pow(a.coeff, b)
new_dict = mapvalues((k, v) -> b*v, a.dict)
if b isa Rational
if isinteger(b)
integer_type = only(typeof(b).parameters)
coeff = a.coeff ^ convert(integer_type, b)
mxhbl marked this conversation as resolved.
Show resolved Hide resolved
else
coeff = 1
merge!(new_dict, Dict(term(^, a.coeff, b) => 1))
mxhbl marked this conversation as resolved.
Show resolved Hide resolved
end
else
coeff = unstable_pow(a.coeff, b)
end

Mul(promote_symtype(^, symtype(a), symtype(b)),
coeff, mapvalues((k, v) -> b*v, a.dict))
coeff, new_dict)
else
Pow(a, b)
end
Expand Down
8 changes: 8 additions & 0 deletions test/rulesets.jl
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@ end
@test simplify(Term(zero, [a])) == 0
@test simplify(Term(zero, [b + 1])) == 0
@test simplify(Term(zero, [x + 2])) == 0

@eqtest simplify(Term(sqrt, [2])) == Term(sqrt, [2])
@eqtest simplify(Term(^, [2, 1//2])) == Term(^, [2, 1//2])
@eqtest simplify(Term(^, [2x, 1//2])) == Term(^, [2, 1//2]) * x^(1//2)
@test simplify(Term(^, [2, 3])) ≈ 8
@test simplify(Term(^, [1//3, 3])) == 1//27
@test simplify(Term(^, [2, 0.5])) ≈ 2^0.5
@test simplify(Term(^, [2.5, 0.25])) ≈ 2.5^(0.25)
end

@testset "LiteralReal" begin
Expand Down
Loading