'Use of variables in SAGE procedure
I am learning how to write SAGE procedures and I am looking at various examples. Here is one for the Method of Bisection (to find a zero of a function:
def method_of_bisection(a, b, n, f, x=x):
c, d = a, b
f(x) = f
for i in range(n):
# compute midpoint, then compare
e = (c + d)/2
if (f(c) > 0 and f(e) > 0) or (f(c) < 0 and f(e) < 0):
c=e
elif f(e) == 0:
c=d=e
break
else:
d=e
return (c, d)
My question is: why do we need to rename a,b to c,d? What is wrong with using instead:
def method_of_bisection(a, b, n, f, x=x):
f(x) = f
for i in range(n):
# compute midpoint, then compare
e = (a+b)/2
if (f(a) > 0 and f(e) > 0) or (f(a) < 0 and f(e) < 0):
a=e
elif f(e) == 0:
a=b=e
break
else:
b=e
return (a,b)
This initial renaming of variables is done in all the examples of SAGE procedures I am looking at, and I am sure there must be a basic "good programming" practice behind it, but I don't know what it is.
Solution 1:[1]
You are correct, you don't need to rename a and b to c and d, respectively. The variables a and b are local variables - local copies inside the scope of f, and modifying them would not affect any global variables.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ashwin Ganesan |