我正在使用Python2.7.6(默认版本为Jun 22 2015, 17:58:13)编写一个小的Python模块,并且使用IPython1.2.1来运行我的程序。
该模块将包含多个基于幂级数的数学函数的计算。我将Python函数定义与Python函数测试分开处理。
下面是我的PowerSeries.py代码:
### Computations of some functions by power series ###
def exp(x):
"""Exponential function"""
exp=1.0
term=1.0
iteration=1
factorial=1
while(abs(term/factorial)>1e-10):
factorial*=iteration
term*=x
exp+=term/factorial
iteration+=1
return exp
def hyperbolicCosine(x):
"""Hyperbolic cosine function"""
cosh=1.0
term=1.0
iteration=1
factorial=1
while(abs(term/factorial)>1e-10):
factorial*=iteration
term*=x
if iteration%2==0:
cosh+=term/factorial
iteration+=1
return cosh
def sine(x):
"""Sine function"""
sine=0.0
term=1.0
iteration=1
factorial=1
while(abs(term/factorial)>1e-10):
factorial*=iteration
term*=x
if iteration%2==1:
sine+=term/factorial
term=-term
iteration+=1
return sine
def cosine(x):
"""Cosine function"""
cosine=1.0
term=1.0
iteration=1
factorial=1
while(abs(term/factorial)>1e-10):
factorial*=iteration
term*=x
if (iteration)%2==0:
term=-term
cosine+=term/factorial
iteration+=1
return cosine
这是我的tests.py代码:
### Tests for PowerSeries Module ###
from math import pi
from PowerSeries import *
# Tests of exponential
print "### Tests of exponential ###"
x=-2
print("x=%f exp(x)=%.10f" % (x,exp(x)))
x=-1
print("x=%f exp(x)=%.10f" % (x,exp(x)))
x=0
print("x=%f exp(x)=%.10f" % (x,exp(x)))
x=1
print("x=%f exp(x)=%.10f" % (x,exp(x)))
x=2
print("x=%f exp(x)=%.10f" % (x,exp(x)))
# Tests of hyperbolic cosine
print "### Tests of hyperbolic cosine ###"
x=-2
print("x=%f cosh(x)=%.10f" % (x,hyperbolicCosine(x)))
x=-1
print("x=%f cosh(x)=%.10f" % (x,hyperbolicCosine(x)))
x=0
print("x=%f cosh(x)=%.10f" % (x,hyperbolicCosine(x)))
x=1
print("x=%f cosh(x)=%.10f" % (x,hyperbolicCosine(x)))
x=2
print("x=%f cosh(x)=%.10f" % (x,hyperbolicCosine(x)))
# Tests of sine
print "### Tests of sine ###"
x=0
print("x=%f sin(x)=%.10f" % (x,sine(x)))
x=pi/6
print("x=%f sin(x)=%.10f" % (x,sine(x)))
x=pi/4
print("x=%f sin(x)=%.10f" % (x,sine(x)))
x=pi/3
print("x=%f sin(x)=%.10f" % (x,sine(x)))
x=pi/2
print("x=%f sin(x)=%.10f" % (x,sine(x)))
# Tests of cosine
print "### Tests of cosine ###"
x=0
print("x=%f cos(x)=%.10f" % (x,cosine(x)))
x=pi/6
print("x=%f cos(x)=%.10f" % (x,cosine(x)))
x=pi/4
print("x=%f cos(x)=%.10f" % (x,cosine(x)))
x=pi/3
print("x=%f cos(x)=%.10f" % (x,cosine(x)))
x=pi/2
print("x=%f cos(x)=%.10f" % (x,cosine(x)))
一切正常,直到我添加双曲余弦定义。 执行tests.py文件时,出现一个无法解决的NameError错误:
19 print "### Tests of hyperbolic cosine ###"
20 x=-2
---> 21 print("x=%f cosh(x)=%.10f" % (x,hyperbolicCosine(x)))
22 x=-1
23 print("x=%f cosh(x)=%.10f" % (x,hyperbolicCosine(x)))
NameError: name 'hyperbolicCosine' is not defined
欢迎提供帮助。
tests.py
代码的?可以展示一下具体的命令吗?是在 ipython 解释器内部运行的吗? - Anand S Kumar