Skip to content

Commit f79cbfa

Browse files
rewrote add_with_divs
1 parent 98654b0 commit f79cbfa

File tree

1 file changed

+29
-21
lines changed

1 file changed

+29
-21
lines changed

src/polyform.jl

Lines changed: 29 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -288,22 +288,6 @@ function simplify_div(d)
288288
end
289289
end
290290

291-
#add_divs(x::Div, y::Div) = (x.num * y.den + y.num * x.den) / (x.den * y.den)
292-
#add_divs(x::Div, y) = (x.num + y * x.den) / x.den
293-
#add_divs(x, y::Div) = (x * y.den + y.num) / y.den
294-
#add_divs(x, y) = x + y
295-
function add_divs(x, y)
296-
if isdiv(x) && isdiv(y)
297-
return (x.num * y.den + y.num * x.den) / (x.den * y.den)
298-
elseif isdiv(x)
299-
return (x.num + y * x.den) / x.den
300-
elseif isdiv(y)
301-
return (x * y.den + y.num) / y.den
302-
else
303-
x + y
304-
end
305-
end
306-
307291
function frac_maketerm(T, f, args, metadata)
308292
# TODO add stype to T?
309293
if f in (*, /, \, +, -)
@@ -347,16 +331,40 @@ function add_with_div(x, flatten=true)
347331
(!iscall(x) || operation(x) != (+)) && return x
348332
aa = parent(arguments(x))
349333
!any(isdiv, aa) && return x # no rewrite necessary
350-
nondiv_result = 0
351-
div_result = 0
334+
335+
# find and multiply all denominators
336+
dens = ArgsT()
352337
for a in aa
338+
isdiv(a) || continue
339+
push!(dens, a.den)
340+
end
341+
den = mul_worker(dens)
342+
343+
# add all numerators
344+
div_idx = 1
345+
nums = ArgsT()
346+
for a in aa
347+
# if it is a division, we don't want to multiply the numerator by
348+
# its own denominator, so temporarily overwrite the index in `dens`
349+
# that is the denominator of this term (tracked by `div_idx`), multiply
350+
# and voila! numerator. Remember to reset `dens` at the end.
353351
if isdiv(a)
354-
div_result = quick_cancel(add_divs(div_result, a))
352+
_den = dens[div_idx]
353+
dens[div_idx] = a.num
354+
_num = mul_worker(dens)
355+
dens[div_idx] = _den
356+
div_idx += 1
355357
else
356-
nondiv_result += a
358+
_num = den * a
357359
end
360+
push!(nums, _num)
361+
end
362+
num = add_worker(nums)
363+
364+
if flatten
365+
num, den = quick_cancel(num, den)
358366
end
359-
flatten ? quick_cancel(add_divs(div_result, nondiv_result)) : div_result + nondiv_result
367+
return num / den
360368
end
361369
"""
362370
flatten_fractions(x)

0 commit comments

Comments
 (0)