我如何将一个ease in out函数从c++翻译成python ?

How would I translate an ease in out function from c++ to python?

本文关键字:函数 out c++ 翻译 python in ease 一个      更新时间:2023-10-16

我一直在尝试将一个函数从c++翻译到Python有一段时间了,但我不能很好地理解这个函数,无法自己翻译。

//C++
float Cubic::easeInOut(float t,float b , float c, float d) {
    if ((t/=d/2) < 1) return c/2*t*t*t + b;
    return c/2*((t-=2)*t*t + 2) + b;    
}
//Python
def rotate(t, b, c, d):
    t = t/(d/2)
    if (t < 1):
        return c/2*t*t*t + b
    t = t-2
    return c/2*((t)*t*t + 2) + b
编辑:这是我到目前为止得到的,但它没有返回一个从0.0上升到1.0的列表。以前有人用python做过这个吗?

提示:首先,简化c++

struct Cubic { 
    float easeInOut(float t,float b , float c, float d) {
        t = t / (d/2);
        if (t < 1) 
            return c/2*t*t*t + b;
        t = t - 2;
        return c/2*(t*t*t + 2) + b;   
    } 
}

如果你不知道如何把翻译成python,那么你需要学习更多的python。我可以把它翻译成python,我甚至不知道 python

实际上,既然你已经发布了你的python,并且你声称它是错误的,我突然想到python中的所有数字都是(可能,我在这里猜测)双精度,这意味着每次你除以它都会与c++略有不同。快速浏览一下Python文档,上面写着"The / (division) and // (floor division) operators yield the quotient of their arguments.",所以如果你想让它像c++一样工作,显然你应该使用//

如果将所有的数字常量(例如2)替换为它们的等效浮点常量(例如2.0),会有帮助吗?

def rotate(t, b, c, d):
    t = t/(d/2.0)
    if t < 1.0:
        return c/2.0*t*t*t + b
    t = t-2.0
    return c/2.0*((t)*t*t + 2.0) + b

您的代码是一个正确的翻译,但它不打算返回一个列表。这个缓和函数返回给定时间(t)的单个缓和时间值。它被多次调用,其t值从0到d变化,并以平滑(非线性)的方式返回从b到b+c变化的结果。

你想让返回值从0到1,所以你应该用b=0.0和c=1.0来调用它。d值应该设置为要缓过的持续时间。

要获得从0到1的简化值列表,对于从0到10的t,您可以这样做:

[rotate(t,0.0,1.0,10.0) for t in range(11)]
结果:

[0.0, 0.004000000000000001, 0.03200000000000001, 0.108, 0.25600000000000006, 0.5, 0.744, 0.8919999999999999, 0.968, 0.996, 1.0]