Skip to content

numerical error #1

@hailunforthree

Description

@hailunforthree

if the random varible is close to zero, i.e., x->0, the result of pdf is not stable.
import numpy as np
import matplotlib.pyplot as plt

from torchquad import set_up_backend # Necessary to enable GPU support

import torch

if torch.cuda.is_available():

set_up_backend("torch", data_type="float32")

from torchlevy import stable_dist
eps=1e-6

1. 生成噪声样本

alpha = 1.5 # 稳定参数
beta = 0 # 对称
x = torch.linspace(-20,20,10000)
print(x.dtype)
f1 = stable_dist.pdf(x,alpha,beta)

3. 数值求导计算 f_v'(x)

f1_ = (stable_dist.pdf(x+eps,alpha,beta)-stable_dist.pdf(x,alpha,beta))/eps # 计算差分作为近似导数

将导数结果对齐为 bin_centers 的长度

4. 计算 g(x) = f_v'(x) / f_v(x)

threshold = 1e-3 # 避免除零的阈值
g1 = torch.where(f1 > threshold, -f1_ / f1 , 0)

5. 可视化结果

plt.figure(figsize=(20, 12))
plt.plot(x.cpu(),f1_.cpu()-f_, label="g(x) = f_v'(x) / f_v(x)")
plt.xlabel("x")
plt.ylabel("g(x)")
plt.xlim([-1, 1])
plt.legend()
plt.show()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions