我正在使用蒙特卡罗方法进行数值积分。我已经设法使函数工作,但现在我试图将结果存储在矩阵中,所以我可以将所有内容绘制在一起。
这是我的错误: ``Traceback(最近一次调用最后一次): 文件“mcmc.py”,第41行,in result_array = list(fnArea) TypeError:'float'对象不可迭代
这是我的代码:
from math import *
from random import *
import numpy as np
def f(a):
return sin(a)
amin = 0.0
amax = 2.0*pi
numRep = 100 #quanto maior, mais preciso porem mais devagar
bmin = f(amin)
bmax = bmin
for i in range(numRep):
a = amin + (amax - amin) * float(i)/numRep
b = f(a)
if b < bmin: bmin = b
if b > bmax: bmax = b
retArea = (amax - amin)*(bmax - bmin) #definicao da integral
numPontos = 100
soma = 0
for j in range(numPontos):
a = amin + (amax - amin) * random()
b = bmin + (bmax - bmin) * random()
if fabs(b) <= fabs(f(a)):
if f(a) > 0 and b > 0 and b <= f(a):
soma += 1
if f(a) < 0 and b < 0 and b >= f(a):
soma -= 1
fnArea = retArea * float(soma)/numPontos
print (str(fnArea))
result_array = np.empty((0,100))
count = 100
for i in range(count):
fnArea = retArea * (soma)/numPontos
result_array = list(fnArea)
print (result_array)
答案 0 :(得分:0)
您收到错误是因为
result_array = list(fnArea)
在这里,您试图将浮动转换为无效的列表。
这是一个有效的代码,但是我不确定你得到的结果的正确性。
这里我们使result_array成为一个0的零数组,然后根据i替换每一列。
from math import *
from random import *
import numpy as np
def f(a):
return sin(a)
amin = 0.0
amax = 2.0*pi
numRep = 100 #quanto maior, mais preciso porem mais devagar
bmin = f(amin)
bmax = bmin
for i in range(numRep):
a = amin + (amax - amin) * float(i)/numRep
b = f(a)
if b < bmin: bmin = b
if b > bmax: bmax = b
retArea = (amax - amin)*(bmax - bmin) #definicao da integral
numPontos = 100
soma = 0
for j in range(numPontos):
a = amin + (amax - amin) * random()
b = bmin + (bmax - bmin) * random()
if fabs(b) <= fabs(f(a)):
if f(a) > 0 and b > 0 and b <= f(a):
soma += 1
if f(a) < 0 and b < 0 and b >= f(a):
soma -= 1
fnArea = retArea * float(soma)/numPontos
print (str(fnArea))
result_array = np.zeros((1,100))
count = 100
for i in range(count):
fnArea = retArea * (soma)/numPontos
result_array[0,i] = fnArea
print (result_array)
答案 1 :(得分:0)
您收到此错误是因为您尝试将float
对象[编号]转换为list
[可迭代]。
如果您要创建值为fnArea
的列表列表。我已将result_array
声明修改为python列表,而不是numpy数组,并在fnArea
循环中追加for
的值。请参阅下面的答案:
from math import *
from random import *
import numpy as np
def f(a):
return sin(a)
amin = 0.0
amax = 2.0*pi
numRep = 100 #quanto maior, mais preciso porem mais devagar
bmin = f(amin)
bmax = bmin
for i in range(numRep):
a = amin + (amax - amin) * float(i)/numRep
b = f(a)
if b < bmin: bmin = b
if b > bmax: bmax = b
retArea = (amax - amin)*(bmax - bmin) #definicao da integral
numPontos = 100
soma = 0
for j in range(numPontos):
a = amin + (amax - amin) * random()
b = bmin + (bmax - bmin) * random()
if fabs(b) <= fabs(f(a)):
if f(a) > 0 and b > 0 and b <= f(a):
soma += 1
if f(a) < 0 and b < 0 and b >= f(a):
soma -= 1
fnArea = retArea * float(soma)/numPontos
print (str(fnArea))
result_array = []
count = 100
for i in range(count):
fnArea = retArea * (soma)/numPontos
print fnArea
result_array.append([fnArea])
print (result_array)