I'm confused by the fact that variables defined inside functions can
"leak out" and become global variables. Here's what I've noticed.

(1) I create a file called "steiner.py" for finding the Steiner point
given three points in the plane. Here's my code:


def dist(p,q):
    """
    Eulidean distance between two points
    """
    n = len(p)
    d2 = sum( (p[k]-q[k])**2 for k in range(n) )
    return sqrt(d2)

def steiner(a,b,c):
    """
    Given three points in the plane, find the point p that minimizes
    the sum of the distances to those three points.
    """
    x = var('x')
    y = var('y')
    p = (x,y)  # unknown point

    # objective function to minimize
    obj = dist(p,a) + dist(p,b) + dist(p,c)

    # start search at center of mass of the three points
    p0 = ( (a[0]+b[0]+c[0])/3., (a[1]+b[1]+c[1])/3. )

    print "Starting optimiztion at", p0
    print obj.subs(x=p0[0], y=p0[1])

    return minimize(obj,p0)


(2) I attach this file in a Sage session. If I have global variables x
or y, they are wiped out when I invoke the steiner function. Here's a
transcript.


$ sage
----------------------------------------------------------------------
| Sage Version 4.7.2, Release Date: 2011-10-29                       |
| Type notebook() for the GUI, and license() for information.        |
----------------------------------------------------------------------
sage: attach steiner.py
sage: x = [1,2,3]
sage: y = [4,5,6]
sage: x
[1, 2, 3]
sage: y
[4, 5, 6]
sage: steiner((1,1), (2,3), (5,2))
Starting optimiztion at (2.6666666666666665, 2.0)
5.4788343901030965
Optimization terminated successfully.
         Current function value: 5.303240
         Iterations: 6
         Function evaluations: 7
         Gradient evaluations: 7
(2.20179756615, 2.46316721759)
sage: x
x
sage: y
y

My apologies if this is something already covered, but it's confusing
and not the behavior I would expect. Other variables defined inside
functions don't "leak out" like this.


-- 
To post to this group, send email to sage-support@googlegroups.com
To unsubscribe from this group, send email to 
sage-support+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/sage-support
URL: http://www.sagemath.org

Reply via email to