Ask Your Question

# code snippet resp. simplify and factor

this doesn't work

var('c')
mat=matrix([[1,0],[0,c]])
xy0=vector([c,1])
r0=-mat*xy0
p0=r0
for k in range(2):
la=r0*p0/(p0*mat*p0)
xy1=xy0+la*p0
print xy1
if xy1[0]!=0:
xy1[0]=xy1[0].factor()
if (xy1[1])!=0:
xy1[1]=xy1[1].factor()
print xy1
r1=(r0-la*mat*p0)
p1=r1+r1*r1/(r0.dot_product(r0))*p0
p1=p1.simplify_full()
p0=p1
r0=r1
xy0=xy1
print '--------------------'


but this works

var('c')
mat=matrix([[1,0],[0,c]])
xy0=vector([c,1])
r0=-mat*xy0
p0=r0
for k in range(2):
la=r0*p0/(p0*mat*p0)
xy1=xy0+la*p0
print xy1
xy1=xy1.simplify_full()   # <<<<<<<<< inserted this command
if xy1[0]!=0:
xy1[0]=xy1[0].factor()
if (xy1[1])!=0:
xy1[1]=xy1[1].factor()
print xy1
r1=(r0-la*mat*p0)
p1=r1+r1*r1/(r0.dot_product(r0))*p0
p1=p1.simplify_full()
p0=p1
r0=r1
xy0=xy1
print '--------------------'

edit retag close merge delete

## Comments

What is your question (or suggestion) ?

( 2018-06-30 18:31:26 -0600 )edit

## 1 answer

Sort by ยป oldest newest most voted

Yes, sometimes one has to oblige the machine to simplify! Consider the following code:

var('c')
mat = matrix( [[1,0], [0,c]] )
xy0 = vector( [c,1] )
r0  = -mat*xy0
p0  = r0

for k in range(2):
la  = r0*p0/(p0*mat*p0)
xy1 = xy0 + la*p0

# xy1 = xy1.simplify_full()   # <<<<<<<<< inserted this command
for j in range(2):
print ( "k=%(k)s j=%(j)s bool(xy1[%(j)s])=%(bool1)s bool(xy1[%(j)s] != 0)=%(bool2)s"
% {'k': k, 'j': j, 'bool1': bool(xy1[j]), 'bool2': bool(xy1[j] != 0)} )
if xy1[j]:    # changed!
xy1[j] = xy1[j].factor()

r1  = r0 - la*mat*p0
p1  = r1 + r1*r1/(r0.dot_product(r0))*p0
p1  = p1.simplify_full()
p0  = p1
r0  = r1
xy0 = xy1
print


Results:

k=0 j=0 bool(xy1[0])=True bool(xy1[0] != 0)=True
k=0 j=1 bool(xy1[1])=True bool(xy1[1] != 0)=True

k=1 j=0 bool(xy1[0])=False bool(xy1[0] != 0)=True
k=1 j=1 bool(xy1[1])=False bool(xy1[1] != 0)=True


So, for k=1 the condition xy1[0] != 0 is above True, since "at the first glance" the code is not completely evaluated. But using xy1[j] instead in the if-condition makes sage convert it to a boolean, and this conversion computes bool(xy1[0]), which is False. (The error comes in the if-block than immediately from factoring the zero.)

Moral: Write the code in a "solid way", understand and test the if-conditions for the given purpose. Sage was at some places educated to do the "quick thing", since always applying the full simplification may not be what we want.

more

## Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

## Stats

Asked: 2018-06-30 06:41:03 -0600

Seen: 66 times

Last updated: Jul 05 '18