Expression substitution fails: why?
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).
Updated code
# First declare a bunch of variables
var('A, L, G, R', domain='positive')
var('f, k, n, q, u', domain='positive')
var('beta', domain='positive')
var('gamma', domain='positive')
# 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_1 = (expr_complex.real()^2+expr_complex.imag()^2).factor()
show(expr_real_1)
show(expr_real_1.subs(f=2*beta))
# This approach is fine too
expr_real_2 = (sqrt(expr_complex.real()^2+expr_complex.imag()^2)^2).factor()
print(bool(expr_real_1 == expr_real_2))
show(expr_real_2.subs(f=2*beta))
# This approach causes Sage to run out of memory
expr_real_3 = ((sqrt(expr_complex.real()^2+expr_complex.imag()^2).factor())^2).factor()
print(bool(expr_real_3 == expr_real_1))
print(bool(expr_real_3 == expr_real_2))
show(expr_real_3.subs(f=2*beta)) # This step yields a MemoryError (verified on SageCell)
To check what Sage version runs at SageCell, use
print(version())
. : )