问题
What do I have to do to make this code run in Python? I got the code from here. If I run it in a SageMath workbook on CoCalc, it works with no adjustment needed. When I run it in Python after importing sage and numpy, I get various name and attribute errors.
def mean_x(factor, values):
return sum([cos(2*pi*v/factor) for v in values])/len(values)
def mean_y(factor, values):
return sum([sin(2*pi*v/factor) for v in values])/len(values)
def calculatePeriodAppeal(factor, values):
mx = mean_x(factor, values)
my = mean_y(factor, values)
appeal = sqrt(mx^2+my^2)
return appeal
def calculateBestLinear(factor, values):
mx = mean_x(factor, values).n()
my = mean_y(factor, values).n()
y0 = factor*atan2(my,mx)/(2*pi).n()
err = 1-sqrt(mx^2+my^2).n()
return [factor*x + y0, err]
def calculateGCDAppeal(factor, values):
mx = mean_x(factor, values)
my = mean_y(factor, values)
appeal = 1 - sqrt((mx-1)^2+my^2)/2
return appeal
testSeq = [0,125,211,287,408,520,650,735,816,942,1060]
gcd = calculateGCDAppeal(x,testSeq)
agcd = find_local_maximum(gcd,2,100)
print(agcd)
plot(gcd,(x,2,100))
回答1:
The first error is
RuntimeError: Use ** for exponentiation, not '^', which means xor
in Python, and has the wrong precedence.
Once that is fixed, there are various missing imports.
Find each of them with Sage's import_statements
function.
sage: import_statements(x)
from sage.calculus.predefined import x
sage: import_statements(sum)
from sage.misc.functional import symbolic_sum
sage: import_statements(cos)
from sage.functions.trig import cos
sage: import_statements(sin)
from sage.functions.trig import sin
In the end the code might look like:
from sage.calculus.predefined import x
from sage.misc.functional import symbolic_sum as sum
from sage.functions.trig import cos, sin
def mean_x(factor, values):
return sum(cos(2*pi*v/factor) for v in values) / len(values)
def mean_y(factor, values):
return sum(sin(2*pi*v/factor) for v in values) / len(values)
def calculatePeriodAppeal(factor, values):
mx = mean_x(factor, values)
my = mean_y(factor, values)
appeal = sqrt(mx**2 + my**2)
return appeal
def calculateBestLinear(factor, values):
mx = mean_x(factor, values).n()
my = mean_y(factor, values).n()
y0 = factor*atan2(my, mx)/(2*pi).n()
err = 1-sqrt(mx**2 + my**2).n()
return [factor*x + y0, err]
def calculateGCDAppeal(factor, values):
mx = mean_x(factor, values)
my = mean_y(factor, values)
appeal = 1 - sqrt((mx - 1)**2 + my**2)/2
return appeal
testSeq = [0, 125, 211, 287, 408, 520, 650, 735, 816, 942, 1060]
gcd = calculateGCDAppeal(x, testSeq)
agcd = find_local_maximum(gcd, 2, 100)
print(agcd)
plot(gcd, (x, 2, 100))
Search Ask Sage for "import_statements", some answers there go into more detail on this topic.
- Search import_statements on Ask Sage
来源:https://stackoverflow.com/questions/63820416/how-can-i-translate-this-sagemath-code-to-run-in-python