因此,当我尝试运行/构建代码时,它会卡在该阶段,没有显示错误,但代码没有发生任何事情,因此我尝试调试它,并尝试让它绘制这样的图表,
这是我试图运行的代码。当我试图构建它时,没有输出。更新后,我得到了一个ValueError:一个数学域错误,我想知道如何在我的代码中修复它,以便它可以输出上面的图形。
Traceback (most recent call last):
File "file_location", line 19, in g
return (f(a + (2 * j - 2) * h) + 4 * f(a + (2 * j - 1) * h) + f(a + (2 * j) * h))
File "file_location", line 9, in f
return math.acos(arg_cos / (1 + 2 * arg_cos))
ValueError: math domain error
代码
import math
import numpy as np
import time
import multiprocessing as mp
import matplotlib.pyplot as plt
def f(x):
return math.acos(math.cos(x) / (1 + 2 * math.cos(x)))
b = math.pi / 2
a = 0
exact = math.pi ** 2 / 16
h = (b - a)
def g(j):
global a
global h
return (f(a + (2 * j - 2) * h) + 4 * f(a + (2 * j - 1) * h) + f(a + (2 * j) * h))
if __name__ == '__main__':
mp.freeze_support() #needed for Windows
pool = mp.Pool(processes=mp.cpu_count())
serial_times = []
parallel_times = []
intervals = []
for i in range(1, 10):
n = 10 ** i
h = (b - a) / n
N = int(n / 2)
intervals.append(N)
start_time = time.time()
p = pool.map(g, np.linspace(1, N, N, dtype=np.int32))
P = (h / 3) * np.sum(p, dtype=np.float32)
elapsedTime = time.time() - start_time
parallel_times.append(elapsedTime)
start_time = time.time()
S = 0
for j in range(1, N+1):
S += f(a + (2 * j - 2) * h) + 4 * f(a + (2 * j - 1) * h) + f(a + (2 * j) * h)
S *= h / 3
elapsedTime = time.time() - start_time
serial_times.append(elapsedTime)
#Plotting
plt.plot(intervals, serial_times, label='Serial Computation')
plt.plot(intervals, parallel_times, label='Parallel Computation')
plt.xlabel('Interval Count (N)')
plt.ylabel('Runtime (s)')
plt.xscale('log')
plt.yscale('log')
plt.title('Simpson\'s Rule Computation Time vs Interval Count')
plt.legend()
plt.show()
1条答案
按热度按时间owfi6suc1#
math.acos()
仅为-1和1之间的值定义。如果使用该范围之外的值调用math.acos()
,则会发生此错误。