Trying to solve my problem (Sympy : How is it possible to simplify power of sum?), I found a simple example where powsimp does not work.
In this case, the power simplification is done
x,y,n=sp.symbols("x y n",positive=True,real=True)
expr=sp.Pow(x,n)*sp.Pow(y,-n)
expr.powsimp()
But not in this case :
expr=sp.Pow(x,n+1)*sp.Pow(y,-n-1)
expr.powsimp()
Is it possible to do power simplification when the exponent is an expression (real and positive of course) ?
powsimp should look for such cases, but until then, converting the exponent to a single variable (and subs will work out the relationship for you for the negated case):
>>> expr
x**(n + 1)*y**(-n - 1)
>>> powsimp(expr.subs(n + 1, var('z',positive=1))).subs(z, n + 1)
(x/y)**(n + 1)
Related
Given an expression, how do I find (after simplifications if needed) if the expression contains the complex number I which is the square root of −1?
In Maple, this is done using the check has(expression,I); see its help page.
In Mathematica, this is done using the check If[FreeQ[expression, Complex], for example: How to check if expression contains a Complex expression?
But I am not sure how to do similar thing in SymPy.
Using expression.is_complex does not return True even if I in the expression. Also since real is subset of complex, this is not a correct test anyway.
I need to check for an explicit I that shows up in the expression anywhere (after simplification).
Here is an example: I am using SymPy 1.5.
from sympy import *
from sympy.abc import z
ex1=(-(((1 + 3*I) + sqrt(2))*cos(z/2)) + ((1 + I) - I*sqrt(2))*sin(z/2))/(((1 + I) + sqrt(2))*cos(z/2) + I*((-1 -I) + sqrt(2))*sin(z/2))
print(ex1.is_complex)
#None
print(simplify(ex1).is_complex)
#None
This is in Maple, for reference:
restart;
result:=(-(((1 + 3*I) + sqrt(2))*cos(z/2)) + ((1 + I) - I*sqrt(2))*sin(z/2))/(((1 + I) + sqrt(2))*cos(z/2) + I*((-1 -I) + sqrt(2))*sin(z/2));
has(simplify(result),I)
Which gives
How to do the above in SymPy?
has checks whether an expression contains some subexpression, such as I:
ex1.has(I) # True
sin(z).has(I) # False
(sin(z)+I).has(I) # True
Note that this does not take into account simplifications that might get rid of the I.
As for checks like is_complex, they consider all possible values of the input variable and return None if there is no clear answer (or if SymPy does not see a relevant simplification). Also, in your case, you want to use is_real (since real numbers are also complex in SymPy’s sense, as you noted). For illustration, consider the following:
z = Symbol("z")
(z+1).is_real # None
(z+I).is_real # None
z = Symbol("z", real=True)
(z+1).is_real # True
(z+I).is_real # False
I want to take some polynomial f and remove all of it's cyclotomic factors, and then look at the resulting polynomial (say g). I'm aware of polcyclofactors and the current code I have tried is:
c(f)=polcyclofactors(f)
p(f)=prod(i=1,#c(f),c(f)[i])
g(f)=f/p(f)
The issue I have is that polcyclofactors doesn't take into account multiplicity of the cyclotomic factors. For example:
f=3*x^4 + 8*x^3 + 6*x^2 - 1
g(f)
= 3*x^3 + 5*x^2 + x - 1
But
factor(f)
=
[ x + 1 3]
[3*x - 1 1]
Is there any way to be able to nicely include multiple cyclotomic factors of f to divide by? Or will I have to look at factorising f and try and removing cyclotomic factors that way?
The following two suggestions are based on repeating the divisions until no more can be done (they are both very similar).
Suggestion 1:
r(f)={my(c); while(c=polcyclofactors(f); #c, f=f/vecprod(c)); f}
Suggestion 2:
r(f)={my(g=vecprod(polcyclofactors(f))); while(poldegree(g), f=f/g; g=gcd(f,g)); f}
Another suggestion without a loop:
r(f)={my(g=vecprod(polcyclofactors(f))); numerator(f/g^(poldegree(f)))}
Now a version that is probably superior: For each factor valuation can be used to get the required power.
r(f)={f/vecprod([t^valuation(f,t) | t<-polcyclofactors(f)])}
I'm trying to write an if statement like this
if(denominator([(i-1)! + 1] / i)-1,print(hi),print(ho))
i can be any integer, for example 10. When I set i to 10 it gives this error:
? [(x-1)! + 1] / x
*** this should be an integer: [(x-1)!+1]/x
^-----------
I really only need to check if [(x-1)! + 1] / x is an integer or not. The denominator thing is what I came up with, I also tried Mod but couldn't get that working either.
It seems that you are confused with the names x and i.
Please, see that expression below works properly:
i = 10;
print([(i-1)! + 1] / i);
gp > [362881/10]
I'm not sure what the error was but I ended up using a floor function for determining if it was an integer or not.
You could use:
print(if(((i-1)! + 1) % i, "hi", "ho"))
If i (in your question x) is not an integer, you get an error from the ! (factorial) operator (but see gamma as well).
Do not use [] here, it creates a vector.
The opreator % which I used, gives the remainder. For example 11 % 4 gives the integer 3. In comparison Mod(11, 4) is not an ordinary integer, it is a member of the ring Z/4Z (integers modulo 4). That is very useful in many cases.
I supposed you wanted to write out strings, so I used quotes ". If hi and ho are variables, omit the quotes of course.
I'm currently having trouble understanding how to make imaginary numbers appear when I'm doing the quadratic equation. My assignment is to make the quadratic equation, and get imaginary numbers but I'm having an extremely difficult time getting there.
any help you can offer would be great!
Here is the code i currently have:
import math
print "Hello, please insert 3 numbers to insert into the quadratic equation."
a = input("Please enter the first value: ")
b = input("Please enter the second value: ")
c = input("Please enter the third value: ")
rootValue = b**2 - 4*a*c
if rootValue < 0:
print (-b-(rootValue)**(.5)) / (2 * a)
if rootValue > 0:
print ((-b + (rootValue)**(1/2)) /(2 * a))
if rootValue == 0:
print -b/(2*a)
please help!!! i'm so stuck right now.
I think you have to do something with the problem if rootValue < 0; but I'm not sure how to do that.
I'm also not allowed to use 'import cmath', I'm supposed to make it so that you can just do this this way.
There are a couple of problems with your code besides how to represent complex numbers. Remember that if rootValue <> 0, there are ALWAY TWO roots:
(-b +/- sqrt(rootValue)/ 2a
It doesn't matter if the rootValue is positive or negative, there's still two roots. You are branching and only providing one of the two roots in each case. No need for the first two if statements
To make rootValue complex, so that you can have complex result when you take the square root, either set it equal to complex(b2 - 4*a*c, 0) or to (b2 - 4*a*c, 0) + 0j.
You want to raise things to the 0.5 power for each of the two roots, NOT the (1/2) power, as you've done in one statement
For completeness, you may want to deal with the a = 0 case.
If you still have problems, let us know.
What would be the most efficient algorithm to solve a linear equation in one variable given as a string input to a function? For example, for input string:
"x + 9 – 2 - 4 + x = – x + 5 – 1 + 3 – x"
The output should be 1.
I am considering using a stack and pushing each string token onto it as I encounter spaces in the string. If the input was in polish notation then it would have been easier to pop numbers off the stack to get to a result, but I am not sure what approach to take here.
It is an interview question.
Solving the linear equation is (I hope) extremely easy for you once you've worked out the coefficients a and b in the equation a * x + b = 0.
So, the difficult part of the problem is parsing the expression and "evaluating" it to find the coefficients. Your example expression is extremely simple, it uses only the operators unary -, binary -, binary +. And =, which you could handle specially.
It is not clear from the question whether the solution should also handle expressions involving binary * and /, or parentheses. I'm wondering whether the interview question is intended:
to make you write some simple code, or
to make you ask what the real scope of the problem is before you write anything.
Both are important skills :-)
It could even be that the question is intended:
to separate those with lots of experience writing parsers (who will solve it as fast as they can write/type) from those with none (who might struggle to solve it at all within a few minutes, at least without some hints).
Anyway, to allow for future more complicated requirements, there are two common approaches to parsing arithmetic expressions: recursive descent or Dijkstra's shunting-yard algorithm. You can look these up, and if you only need the simple expressions in version 1.0 then you can use a simplified form of Dijkstra's algorithm. Then once you've parsed the expression, you need to evaluate it: use values that are linear expressions in x and interpret = as an operator with lowest possible precedence that means "subtract". The result is a linear expression in x that is equal to 0.
If you don't need complicated expressions then you can evaluate that simple example pretty much directly from left-to-right once you've tokenised it[*]:
x
x + 9
// set the "we've found minus sign" bit to negate the first thing that follows
x + 7 // and clear the negative bit
x + 3
2 * x + 3
// set the "we've found the equals sign" bit to negate everything that follows
3 * x + 3
3 * x - 2
3 * x - 1
3 * x - 4
4 * x - 4
Finally, solve a * x + b = 0 as x = - b/a.
[*] example tokenisation code, in Python:
acc = None
for idx, ch in enumerate(input):
if ch in '1234567890':
if acc is None: acc = 0
acc = 10 * acc + int(ch)
continue
if acc != None:
yield acc
acc = None
if ch in '+-=x':
yield ch
elif ch == ' ':
pass
else:
raise ValueError('illegal character "%s" at %d' % (ch, idx))
Alternative example tokenisation code, also in Python, assuming there will always be spaces between tokens as in the example. This leaves token validation to the parser:
return input.split()
ok some simple psuedo code that you could use to solve this problem
function(stinrgToParse){
arrayoftokens = stringToParse.match(RegexMatching);
foreach(arrayoftokens as token)
{
//now step through the tokens and determine what they are
//and store the neccesary information.
}
//Use the above information to do the arithmetic.
//count the number of times a variable appears positive and negative
//do the arithmetic.
//add up the numbers both positive and negative.
//return the result.
}
The first thing is to parse the string, to identify the various tokens (numbers, variables and operators), so that an expression tree can be formed by giving operator proper precedences.
Regular expressions can help, but that's not the only method (grammar parsers like boost::spirit are good too, and you can even run your own: its all a "find and recourse").
The tree can then be manipulated reducing the nodes executing those operation that deals with constants and by grouping variables related operations, executing them accordingly.
This goes on recursively until you remain with a variable related node and a constant node.
At the point the solution is calculated trivially.
They are basically the same principles that leads to the production of an interpreter or a compiler.
Consider:
from operator import add, sub
def ab(expr):
a, b, op = 0, 0, add
for t in expr.split():
if t == '+': op = add
elif t == '-': op = sub
elif t == 'x': a = op(a, 1)
else : b = op(b, int(t))
return a, b
Given an expression like 1 + x - 2 - x... this converts it to a canonical form ax+b and returns a pair of coefficients (a,b).
Now, let's obtain the coefficients from both parts of the equation:
le, ri = equation.split('=')
a1, b1 = ab(le)
a2, b2 = ab(ri)
and finally solve the trivial equation a1*x + b1 = a2*x + b2:
x = (b2 - b1) / (a1 - a2)
Of course, this only solves this particular example, without operator precedence or parentheses. To support the latter you'll need a parser, presumable a recursive descent one, which would be simper to code by hand.