数组初始化方式与decimal.InvalidOperation
- 调用函数
- 主函数: 数组声明不同带来的报错与否
- 1. 报错decimal.InvalidOperation的数组初始化版本
- 2. 可行的初始化版本
- 输出结果
- 1. 报错时的内容
- 2. 正常的输出计算结果
- 原因(是否是数组与列表不同引起(?
调用函数
import scipy.misc
import numpy as np
from decimal import *
x = [i for i in range(10, 110, 10)]
print(x)
def countA_with_n(n):
global A
if n==0:
A[n]=1
else:
for i in range(1, n+1):
if A[n-i]==0:
A[n-i]=countA_with_n(n - i)
#t=(-1) ** (i + 1) * 2 ** ((n - i) * i)* scipy.misc.comb(n, i)*A[n-i]
A[n] = Decimal(A[n]) + Decimal((-1) ** (i + 1)) * Decimal(2 ** ((n - i) * i)) * Decimal(scipy.misc.comb(n, i)) *Decimal(A[n-i])
#A[n]+=t
return A[n]
主函数: 数组声明不同带来的报错与否
1. 报错decimal.InvalidOperation的数组初始化版本
#主函数
for a in x:
A = np.zeros(a+1)
#前40可以计算,50时会报错‘decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]’
#A = [0]*(a+1) #可行的声明方法
print(str(a),str(countA_with_n(a)))
2. 可行的初始化版本
for a in x:
A = [0]*(a+1) #可行的声明方法
print(str(a),str(countA_with_n(a)))
输出结果
1. 报错时的内容
10 4.175098976430598e+18
20 2.3448804510510887e+72
30 2.7148544371675283e+158
C:...py:18: DeprecationWarning: `comb` is deprecated!
Importing `comb` from scipy.misc is deprecated in scipy 1.0.0. Use `scipy.special.comb` instead.
A[n] = Decimal(A[n]) + Decimal((-1) ** (i + 1)) * Decimal(2 ** ((n - i) * i)) * Decimal(scipy.misc.comb(n, i)) *Decimal(A[n-i])
40 1.1241428263057385e+276
Traceback (most recent call last):
File "C:xxx.py", line 65, in <module>
print(str(a),str(countA_with_n(a)))
File "...", line 16, in countA_with_n
A[n-i]=countA_with_n(n - i)
File "...", line 16, in countA_with_n
A[n-i]=countA_with_n(n - i)
File "...", line 16, in countA_with_n
A[n-i]=countA_with_n(n - i)
[Previous line repeated 2 more times]
File "...", line 18, in countA_with_n
A[n] = Decimal(A[n]) + Decimal((-1) ** (i + 1)) * Decimal(2 ** ((n - i) * i)) * Decimal(scipy.misc.comb(n, i)) *Decimal(A[n-i])
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]
2. 正常的输出计算结果
DeprecationWarning: `comb` is deprecated!
Importing `comb` from scipy.misc is deprecated in scipy 1.0.0. Use `scipy.special.comb` instead.
A[n] = Decimal(A[n]) + Decimal((-1) ** (i + 1)) * Decimal(2 ** ((n - i) * i)) * Decimal(scipy.misc.comb(n, i)) *Decimal(A[n-i])
10 4175098976430598143
20 2.344880451051088988152559846E+72
30 2.714854437167529438448086150E+158
40 1.124142826305737256464230893E+276
50 7.150572516568295733815015286E+424
60 4.231846207434397246471425291E+604
70 1.670508589429661015982839133E+815
80 3.469441880795996245588913622E+1056
90 3.173623968493402552666007937E+1328
100 1.113552460282985747462212849E+1631
原因(是否是数组与列表不同引起(?
参看 数组与列表的区别