使用 numpy,我试图了解可以从 float64 向下转换为 float32 的最大值是多少,精度损失小于或等于 0.001。
由于在网上找不到简单的解释,我很快就想出了这段代码来测试:
result = {}
for j in range(1,1000):
for i in range (1, 1_000_000):
num = i + j/1000
x=np.array([num],dtype=np.float32)
y=np.array([num],dtype=np.float64)
if abs(x[0]-y[0]) > 0.001:
result[j] = i
break
Run Code Online (Sandbox Code Playgroud)
根据结果,似乎任何 <32768 的正值都可以安全地从 float64 向下转换为 float32,并且精度损失可以接受(给定 <=0.001 的标准)
它是否正确 ?有人可以解释一下背后的数学原理吗?
多谢
I would like to define a decorator with a parameter that raises an error if the parameter is missing.
Here's a naive attempt on a simplified example:
def decorator_with_arg(a=None):
if a is None :
raise ValueError("Missing argument in decorator")
def decorator(func):
def wrapped_func(x):
return func(x+ a)
return wrapped_func
return decorator
Run Code Online (Sandbox Code Playgroud)
But when I use this decorator without a parameter it's not raising any errors:
@decorator_with_arg
def simple_func(x):
return 2*x
simple_func(1)
Run Code Online (Sandbox Code Playgroud)
How can I raise an exception?