gpt4 book ai didi

python - 如何在python中实现平滑的钳位功能?

转载 作者:太空狗 更新时间:2023-10-29 21:28:07 25 4
gpt4 key购买 nike

clamp函数是clamp(x, min, max) = min if x < min, max if x > max, else x

我需要一个函数,它的行为类似于 clamp 函数,但它是平滑的(即具有连续导数)。

最佳答案

您要找的是类似 Smoothstep 的东西函数,它有一个自由参数 N,给出“平滑度”,即有多少导数应该是连续的。它是这样定义的:

enter image description here

这在几个库中使用,可以在 numpy 中实现为

import numpy as np
from scipy.special import comb

def smoothstep(x, x_min=0, x_max=1, N=1):
x = np.clip((x - x_min) / (x_max - x_min), 0, 1)

result = 0
for n in range(0, N + 1):
result += comb(N + n, n) * comb(2 * N + 1, N - n) * (-x) ** n

result *= x ** (N + 1)

return result

在给定 N=0(0 次可微分)的情况下,它简化为常规钳位函数,并随着 N 的增加而增加平滑度。您可以像这样想象它:

import matplotlib.pyplot as plt

x = np.linspace(-0.5, 1.5, 1000)

for N in range(0, 5):
y = smoothstep(x, N=N)
plt.plot(x, y, label=str(N))

plt.legend()

结果如下:

enter image description here

关于python - 如何在python中实现平滑的钳位功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45165452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com