简体   繁体   English

如何在python中定义周期函数?

[英]How to define periodic function in python?

how can you define a periodic function in python, eg the "sawtooth" function?你怎么能在python中定义一个周期函数,例如“锯齿”函数?

f(x) = x, for –π < x < π and 2-pi periodically continued on IR f(x) = x,对于 –π < x < π 和 2-pi 在 IR 上周期性地继续

Can you do this with a lambda function?你能用 lambda 函数做到这一点吗?

as a normal function you can use modulo ( % ) also with float:作为普通函数,您也可以将模数 ( % ) 与浮点数一起使用:

from math import pi

def f(x):
    return (x+pi) % (2*pi) - pi

this easily translates to a lambda expression:这很容易转化为 lambda 表达式:

lambda x: (x+pi) % (2*pi) - pi

You can make use of decorators:您可以使用装饰器:

def periodically_continued(a, b):
    interval = b - a
    return lambda f: lambda x: f((x - a) % interval + a)

@periodically_continued(-1, 1)
def f(x):
    return x

g = periodically_continued(0, 1)(lambda x: -x)

assert f(2.5) == 0.5
assert g(2.5) == -0.5

You could write a function that takes a function and a period, and returns a function:您可以编写一个函数,它接受一个函数和一个句点,并返回一个函数:

import math

def periodic_function(func, period, offset):
    return lambda x: func( ((x - offset) % period ) + offset )

and use that then:然后使用它:

sawtooth = periodic_function(lambda x: x, 2*math.pi, math.pi)

A very simple way is to limit the inputs to the first period.一个非常简单的方法是将输入限制在第一个时期。 Iteratively remove one period until the input falls within the defined values.迭代删除一个周期,直到输入落在定义的值内。 For example the following example gives a square wave with period 2*pi.例如,以下示例给出了一个周期为 2*pi 的方波。

def f(t):
    while t>2*np.pi:
            t=t-2*np.pi
    if 0.0 <= t <=np.pi:
        return 1.0
    else:
        return -1.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM