简体   繁体   English

Python 中的交变正弦波与方波

[英]Alternating sine wave with square-wave in Python

How do I create a randomly alternating sequence of a sine wave and a square wave in Python?如何在 Python 中创建正弦波和方波的随机交替序列? I need 11,000 timestamps, so I generated a numeric sequence:我需要 11,000 个时间戳,所以我生成了一个数字序列:

t = np.linspace(0, 11000, endpoint = False)

The randonmly alternating sequence of sine wave and square wave needs to look like this: 1正弦波和方波的随机交替序列需要如下所示: 1

I suggest the following approach in which the code continuously generates values and has a certain probability of flipping the wave between square and sine:我建议采用以下方法,其中代码连续生成值并具有一定的概率在方波和正弦波之间翻转:

import math
from random import random

SWITCH_PROBABILITY = 0.25

sine_wave = True

def x_value(t):
    return t

def y_value(t):
    # Determine whether to flip the wave we're producing.
    if random() < SWITCH_PROBABILITY:
        sine_wave = not sine_wave # Flip the wave.

    if sine_wave:
        # We are generating a sine wave.
        return math.sin(t)
    else:
        # We are generating a square wave.
        return math.copysign(1, math.sin(t))

Since I'm not sure how you're generating values or using them, I can't provide more details.由于我不确定您是如何生成或使用它们的,因此我无法提供更多详细信息。 You would probably want to define some time resolution and step through, generating many coordinate pairs as (x_value(t), y_value(t)) .您可能想要定义一些时间分辨率并逐步执行,生成许多坐标对作为(x_value(t), y_value(t))

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

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