我必须在区间[-10,10]中评估函数b = 3x-2,精度从1,0.1,0.01,0.001,0.0001,0.00001等递增,我的目标是达到8以上零(比这个多0.000000001)我正在尝试使用np.linspace()来实现,但它的极限是8个精度数字(8个零,即0.00000001),但是我想达到8个以上的零,理想情况下它将达到10或11个零(我知道这将花费几个小时甚至几天,但目标是达到8个以上的零),我编写了下一个代码,并解释了代码的每个部分:
import numpy as np
import matplotlib.pyplot as plt
from decimal import *
from time import time
file = open("tiempos.txt", "w")
increment = 1
upper_bound = 10
lower_bound = -10
#I'm creating an array to save the values of the increments (1, 0.1, 0.01, 0.001, 0.0001, etc.)
v = []
#Creating an array to save the time that takes to calculate the function with each increment
t = []
for x in range(0, 9):
#Start counting the time that takes each increment
start_time = time()
pts = int((upper_bound - lower_bound)/increment + 1)
#Counting the precision increments
a = np.linspace(lower_bound, upper_bound, pts)
#Calculating the function
b = 3 * a - 2
#introduce the valor of the increment into the array
v.append(increment)
#Divide the increment to get a smaller number
increment = increment/10
#Stop counting the time and seve it
elapsed_time = time() - start_time
#Introduce the time into the array
t.append(elapsed_time)
#write the interval and time into a txt file
file.write("Valor: %.10f " % increment)
file.write("Tiempo: %.10f segundos " % elapsed_time +'\n')
file.close()
print(v)
print(t)
#Graph the time that took each interval
plt.figure(1)
plt.plot(t,v,'*')
plt.show()
我在这部分有问题:
a = np.linspace(lower_bound, upper_bound, pts)
当我到达8个零(0.00000001)时,表示我已经达到np.linspace
的极限
所以我的问题是我怎么能得到一个较小的数字?
答案 0 :(得分:3)
您的问题与np.linspace
无关。 np.linspace
都没有特定的精度。您可以尝试
x = np.linspace(0, 10**(-10), num=10000)
,发现它工作正常。
问题是您的内存不足。每次将增量除以10,数组就会变大10倍。您无能为力。
唯一的方法是,不是预先生成整个a
数组,而是循环生成其元素。例如
while increment > 10**(-12):
# start_timing
for a in range(start, end, increment):
b = 3*a - 2
# stop timing
increment = increment / 10
由于内置范围似乎只接受整数步,并且np.arange
提到它不适用于非整数步,因此您可以创建自己的范围函数。请注意,它必须是生成器,否则会耗尽内存
def my_range(start, stop, step):
current = start
while current < stop:
current += step
yield current