@@ -288,22 +288,6 @@ function simplify_div(d)
288
288
end
289
289
end
290
290
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
-
307
291
function frac_maketerm (T, f, args, metadata)
308
292
# TODO add stype to T?
309
293
if f in (* , / , \ , + , - )
@@ -347,16 +331,40 @@ function add_with_div(x, flatten=true)
347
331
(! iscall (x) || operation (x) != (+ )) && return x
348
332
aa = parent (arguments (x))
349
333
! 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 ()
352
337
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.
353
351
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
355
357
else
356
- nondiv_result += a
358
+ _num = den * a
357
359
end
360
+ push! (nums, _num)
361
+ end
362
+ num = add_worker (nums)
363
+
364
+ if flatten
365
+ num, den = quick_cancel (num, den)
358
366
end
359
- flatten ? quick_cancel ( add_divs (div_result, nondiv_result)) : div_result + nondiv_result
367
+ return num / den
360
368
end
361
369
"""
362
370
flatten_fractions(x)
0 commit comments