Hi, I recently ran into a weird problem where substituting one equation into another sometimes fails with a MemoryError, depending on how the original equation was derived. In the code below I have been able to isolate the issue (my actual code sometimes stumbles on the third approach, and I will have to see how I can change its structure to work around the issue).
In all three approaches, the printout of real_expr is identical. However, when trying to execute the subsequent substitution, it looks like there must be a difference between the three, at least in their internal representation. Note that the MemoryError does not occur when the substitution is simpler, i.e. expr_real.subs(f=2) works fine.
Am I missing something, or is this just a bug?
BTW: I am running Sage 9.1, but the problem also occurs on SageCell (which I presume is running 9.2).
# First declare a bunch of variables
var('A, L, G, R', domain='real')
var('f, k, n, q, u', domain='real')
var('beta', domain='real')
var('gamma', domain='real')
# All variables represent positive real numbers
assume(A > 0)
assume(L > 0)
assume(G > 0)
assume(R > 0)
assume(f > 0)
assume(k > 0)
assume(n > 0)
assume(q > 0)
assume(u > 0)
assume(beta > 0)
assume(gamma > 0)
# Here is a complex expression
expr_complex = (I*R^2*f^3*k*q*A*u
/((2*pi*L*R^2*G*f^4*k^2*q
- 2*pi*L*R^2*G*f^4*q
- 2*pi*L*R^2*beta^2*G*q
+ (2*I*pi*L*R^2*beta*gamma*q + 2*I*pi*L*R*(beta + q))*G*f^3
+ 2*(pi*(beta^2 + 1)*L*R^2*q + pi*L*R*beta*gamma*q + pi*L*beta)*G*f^2
+ (-2*I*pi*L*R^2*beta*gamma*q - 2*I*pi*(beta^2*q + beta)*L*R)*G*f)*n))
# Use three different approaches to derive a real expression from the complex one
# This approach works well
expr_real = (expr_complex.real()^2+expr_complex.imag()^2).factor()
show(expr_real)
show(expr_real.subs(f=2*beta))
# This approach is fine too
expr_real = (sqrt(expr_complex.real()^2+expr_complex.imag()^2)^2).factor()
show(expr_real)
show(expr_real.subs(f=2*beta))
# This approach causes Sage to run out of memory
expr_real = ((sqrt(expr_complex.real()^2+expr_complex.imag()^2).factor())^2).factor()
show(expr_real)
show(expr_real.subs(f=2*beta)) # This step eventually yields a MemoryError (verified on SageCell)