在浮点数数组中的元素之间进行插值 [英] Interpolate between elements in an array of floats

查看:33
本文介绍了在浮点数数组中的元素之间进行插值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个5个浮点的列表,我想将它们用作将pwm发送到LED的值。我想在数组中的元素之间以可变的毫秒数平滑过渡。

I'm getting a list of 5 floats which I would like to use as values to send pwm to an LED. I want to ramp smoothly in a variable amount of milliseconds between the elements in the array.

因此,如果这是我的数组...

So if this is my array...

list = [1.222, 3.111, 0.456, 9.222, 22.333]

我想在3000毫秒内从1.222升至3.111,然后在相同的时间内从3.111升至0.456,当它到达列表的末尾时,我想要第5个元素list逐渐增加到列表的第一个元素,并无限期地继续。

I want to ramp from 1.222 to 3.111 over say 3000 milliseconds, then from 3.111 to 0.456 over the same amount of time, and when it gets to the end of the list I want the 5th element of the list to ramp to the 1st element of the list and continue indefinitely.

推荐答案

另一个版本,类似于dsgdfg的版本(基于(但没有时间上的滞后):

another version, similar to the version of dsgdfg (based on his/her idea), but without timing lag:

import time
list_of_ramp = [1.222, 3.111, 0.456, 9.222, 22.333]

def play_LED(value):
    s = ''
    for i in range(int(value*4)):
        s += '*'           
    print s, value

def interpol(first, second, fract):
    return first + (second - first)*fract

def find_borders(list_of_values, total_time, time_per_step):
    len_list = len(list_of_values)
    total_steps = total_time // time_per_step
    fract = (total_time - total_steps * time_per_step) / float(time_per_step)
    index1 = int(total_steps % len_list)
    return [list_of_values[index1], list_of_values[(index1 + 1) % len_list], fract]

def start_program(list_of_values, time_per_step, relax_time):
    total_start = time.time()
    while True:
        last_time = time.time()
        while time.time() - last_time < relax_time:
            pass
        x = find_borders(list_of_values,time.time(),time_per_step)
        play_LED(interpol(x[0],x[1],x[2]))

start_program(list_of_ramp,time_per_step=5,relax_time=0.5)

这篇关于在浮点数数组中的元素之间进行插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆