如何使用正弦/余弦波返回振荡数 [英] How to use a Sine / Cosine wave to return an oscillating number

查看:438
本文介绍了如何使用正弦/余弦波返回振荡数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java编程的新手,我正在使用Android编写Java 1.6。

I'm new to Java programming, I am programming Java 1.6 with Android.

我有一个简单的函数可以使数字在0到0之间上下变化200.我想把它放到一个正弦函数中,但一直在尝试我的错误。

I have a simple function that makes a number go up and down between 0 and 200. I would like to put this into a Sine function but keep getting errors with what I've been trying.

我希望我的程序通过正弦波y轴更新int(Number1)。

I want my program to update an int (Number1) via a sine wave y axis.

任何想法将以下逻辑更改为正弦函数? (忽略第二个数字)

Any ideas change the following logic into a Sine function? (disregard the 2nd number)

代码:

private int Number1 = 150;
private int Number2 = 0;
private int counter = 0;     

  public void updateNumbers() {   
            if (counter == 0) {
                if (Number1 < 200) {
                    Number1 = Number1 + 50;
                    Number2 = Number2 - 50;
                    if (Number1 >= 200) {
                        counter = 1;
                    }
                }               
            } else if (counter == 1) {
                if (Number2 < 200) {                                       
                    Number1 = Number1 - 50;
                    Number2 = Number2 + 50;               
                    if (Number2 >= 200) {
                        counter = 0;
                    }
                }
            }
        }           


推荐答案

好的,你想要做的是建立一个介于0到200之间的正弦波,但是在什么时期?您是否希望它循环每8次调用?

Okay, so what you want to do is build a sine wave that goes between 0 and 200, but with what period? Did you want it to loop about every 8 calls?

如何利用内置Java Math.sin 功能:

How about this, leveraging the built-in Java Math.sin function:

private static final double PERIOD = 8; // loop every 8 calls to updateNumber
private static final double SCALE = 200; // go between 0 and this

private int _pos = 0;
private int Number1 = 0;

public void updateNumber() {
    _pos++;
    Number1 = (int)(Math.sin(_pos*2*Math.PI/PERIOD)*(SCALE/2) + (SCALE/2));
}

基本上,我们保留一个变量来计算我们已完成的更新数量,并且缩放以匹配正弦波的周期,2 * PI。它充当了真正的sin函数的输入,给出了介于-1和1之间但具有正确频率的东西。然后,为了实际设置数字,我们只需将其缩放到介于-100和100之间,然后加100以将其移动到您想要的0-200范围内。

Basically, we keep a variable that counts how many updates we've done, and scale that to match the period of a sine wave, 2*PI. That acts as the input to the 'real' sin function, giving us something that goes between -1 and 1 but has the right frequency. Then, to actually set the number, we just scale that to be between -100 and 100 and then add 100 to move it to be in the 0-200 range you wanted from the beginning.

(如果双重作用,你不必将数字转换为int,我只是遵循你上面写的精神。)

(You don't have to cast the number to an int if a double works for you, I was just keeping with the spirit of what you wrote above.)

这篇关于如何使用正弦/余弦波返回振荡数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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