반응형
이것은 우리 선생님에게서받은 과제입니다. Simpson 's Rule을 사용하여 함수의 수치 적분을 수행해야합니다. f (x) = x * cos (third_root (x))
그러나 cos
의 내장 함수를 사용하거나 x ** (1.0 / 3.0)
를 사용하여 세 번째 루트를 찾을 수 없습니다.
오류가 발생합니다.
Traceback (most recent call last):
File "path", line 104, in <module>
print simpson(f, 1.0, 50.0, 10)
File "path", line 91, in simpson
I += 2 * f(x) + (4.0 * f(x + h))
File "path", line 101, in f
return x*final_cos(final_3root(x))
File "path", line 72, in final_cos
x = float_mod(x, 2 * pi)
File "path", line 42, in float_mod
k = int(x / a)
TypeError: unsupported operand type(s) for /: 'NoneType' and 'float'
Process finished with exit code 1
그리고 여기 내 코드가 있습니다.
import math
def final_3root(a):
q, m = math.frexp(a)
if 0.5 > q or q > 1.0:
raise ValueError('Math domain error')
x = 0.8968521468804229452995486
factor_1 = 0.6299605249474365823836053
factor_2 = 0.7937005259840997373758528
q_croot = (q / (x * x) + 2.0 * x) / 3.0
q_croot = (q / (q_croot * q_croot) + 2.0 * q_croot) / 3.0
q_croot = (q / (q_croot * q_croot) + 2.0 * q_croot) / 3.0
q_croot = (q / (q_croot * q_croot) + 2.0 * q_croot) / 3.0
if m % 3.0 == 0.0:
m /= 3
answer = math.ldexp(q_croot, m)
elif m % 3 == 1:
m += 2
m /= 3
answer = factor_1 * math.ldexp(q_croot, m)
elif m % 3 == 2:
m += 1
m /= 3
answer = factor_2 * math.ldexp(q_croot, m)
fasit = a ** (1.0 / 3.0)
#----------------------------------------------
def float_mod(x, a):
k = int(x / a)
if (x * a) < 0:
k -= 1
return x - float(k) * a
def ratio_based_cosinus(x):
epsilon = 1.0e-16
previous_Value = 1
return_Value = 1
n = -1
while True:
n += 1
ratio = (-x * x) / (((2 * n) + 1) * ((2 * n) + 2))
previous_Value *= ratio
return_Value += previous_Value
if abs(previous_Value) < epsilon:
break
return return_Value
def final_cos(x):
if isinstance(x, int):
x += 0.0
pi = 3.1415926
x = float_mod(x, 2 * pi)
if x > pi:
return ratio_based_cosinus(-x)
else:
return ratio_based_cosinus(x)
#----------------------------------------------
def simpson(f, a, b, N):
if N & 1:
raise ValueError('Ugyldig tall')
I = 0
h = float((b - a) / N)
x = float(a)
for i in range(0, N / 2):
I += 2 * f(x) + (4.0 * f(x + h))
x += 2 * h
I += float(f(b) - f(a))
I *= h / 3
print "The sum is: ", I
def f(x):
return x*final_cos(final_3root(x))
print simpson(f, 1.0, 50.0, 10)
해결 방법
final_3root
에 return 문이 없습니다.
오류를 자세히 살펴보십시오. x
는 없음
입니다. 다시 추적하면 해당 함수의 반환 값이 사용되는 것을 볼 수 있지만 아무것도 반환하지 않습니다.
참조 페이지 https://stackoverflow.com/questions/22762078
반응형
'파이썬' 카테고리의 다른 글
파이썬 AttributeError: can't set attribute in python (0) | 2020.12.18 |
---|---|
파이썬 Python의 기본 인코딩을 변경 하시겠습니까? (0) | 2020.12.18 |
파이썬 NLTK 불용어 목록 (0) | 2020.12.18 |
파이썬은 문자열에서 x 개의 첫 단어를 얻습니다. (0) | 2020.12.18 |
파이썬 Django, 모델 메서드에서 쿼리 필터링 (0) | 2020.12.18 |
댓글