I wrote the following program in Python 2 to do Newton’s method computations for my math problem set, and while it works perfectly, for reasons unbeknownst to me, when I initially load it in ipython with %run -i NewtonsMethodMultivariate.py, the Python 3 division is not imported. I know this because after I load my Python program, entering x**(3/4) gives “1”. After manually importing the new division, then x**(3/4) remains x**(3/4), as expected. Why is this?
# coding: utf-8
from __future__ import division
from sympy import symbols, Matrix, zeros
x, y = symbols('x y')
X = Matrix([[x],[y]])
tol = 1e-3
def roots(h,a):
def F(s):
return h.subs({x: s[0,0], y: s[1,0]})
def D(s):
return h.jacobian(X).subs({x: s[0,0], y: s[1,0]})
if F(a) == zeros((2,1)):
return a
else:
while (F(a)).norm() > tol:
a = a - ((D(a))**(-1))*F(a)
print a.evalf(10)
I would use Python 3 to avoid this issue, but my Linux distribution only ships SymPy for Python 2. Thanks to the help anyone can provide.
Also, in case anyone was wondering, I haven’t yet generalized this script for nxn Jacobians, and only had to deal with 2×2 in my problem set. Additionally, I’m slicing the 2×2 zero matrix instead of using the command (Thanks eryksun for correcting my notation, which fixed the issue with the zeros function.)zeros(2,1) because SymPy 0.7.1, installed on my machine, complains that “zeros() takes exactly one argument”, though the wiki suggests otherwise. Maybe this command is only for the git version.
Both
ipython -icommand andrun -iinipythoninterpreter ignorefrom __future__ import divisioninprint05.pyscript.In
ipythonconsole:execfileandimportproduce the same result:from __future__ import divisionshould not have effect on the source code from different modules, otherwise it would break code in other modules that don’t expect its presence.Here,
from __future__ import divisionhas effect:The module name in this case is
__main__both insideprint05.pyand in the prompt.Here, the first
print 1/2executes inprint05module, the second one in__main__module so it also works as expected:And here’s something wrong:
The docs for
__future__say:So It might be a bug in
ipythonif its-ioption tries to emulate the same python option.