您可以使用装饰器:
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
Run Code Online (Sandbox Code Playgroud)
作为普通函数,您%也可以将 modulo ( ) 与 float 一起使用:
from math import pi
def f(x):
return (x+pi) % (2*pi) - pi
Run Code Online (Sandbox Code Playgroud)
这很容易转换为 lambda 表达式:
lambda x: (x+pi) % (2*pi) - pi
Run Code Online (Sandbox Code Playgroud)