Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

It seems that, in your expressions, $x$ denotes a real number. If this were the case, you can get the coefficients of I by taking the imaginary part of the expression:

sage: f = x^2 + 2*I*x + 1
sage: g = x^2 + I*x + 1
sage: h = x^2 + 2*x + I
sage: k = x^2 + x + 2*I
sage: assume(x,'real')
sage: for expression in [f, g, h, k]:
....:     print(expression.imag()) 
2*x
x
1
2

Edited. This was the original answer

It seems that, in your expressions, $x$ denotes a real number. If this were the case, you can get the coefficients of I by taking the imaginary part of the expression:

sage: f = x^2 + 2*I*x + 1
sage: g = x^2 + I*x + 1
sage: h = x^2 + 2*x + I
sage: k = x^2 + x + 2*I
sage: assume(x,'real')
sage: for expression in [f, g, h, k]:
....:     print(expression.imag()) 
2*x
x
1
2

New answer. I have improved your approach, based on wildcards. It seems that I is not detected because it is not a symbolic variable. So, we can temporarily transform I into such a variable, find the coefficients of I in the expressions and then restore I:

w0 = SR.wild(0)
var("I")
f = x^2 + 2*I*x + 1
g = x^2 + I*x + 1
h = x^2 + 2*x + I
k = x^2 + x + 2*I
m = sqrt(1-x^2) + I*(1-x^3)^(1/3)
n = sqrt(1-x^2) + 2*I*(1-x^3)^(1/3)
p = x^2 + 2*x - I
q = x^2 + 2*x

expressions = [f, g, h, k, m, n, p, q]
for expression in expressions:
    print("\nExpression: ",expression)
    if expression.has(I):
        if expression.has(w0*I):
            aux = expression.find(w0*I)
            coef = aux[0].match(w0*I)[w0]
        else:
            coef = 1
        print(f"The coefficient of I is {coef}")
    else:
        print("The expression does not contain I")
restore("I")

This is the output:

Expression:  2*I*x + x^2 + 1
The coefficient of I is 2*x

Expression:  I*x + x^2 + 1
The coefficient of I is x

Expression:  x^2 + I + 2*x
The coefficient of I is 1

Expression:  x^2 + 2*I + x
The coefficient of I is 2

Expression:  (-x^3 + 1)^(1/3)*I + sqrt(-x^2 + 1)
The coefficient of I is (-x^3 + 1)^(1/3)

Expression:  2*(-x^3 + 1)^(1/3)*I + sqrt(-x^2 + 1)
The coefficient of I is 2*(-x^3 + 1)^(1/3)

Expression:  x^2 - I + 2*x
The coefficient of I is -1

Expression:  x^2 + 2*x
The expression does not contain I