如何使用正弦/余弦波返回振荡数

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

我有一个简单的函数,使一个数字在0到200之间上下移动。我想把它放到一个正弦函数中,但不断出现我一直在尝试的错误。

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

任何想法都将以下逻辑转换为正弦函数? (无视第二个号码)

码:

private int Number1 = 150; private int Number2 = 0; private int counter = 0; public void updateNumbers() { if (counter == 0) { if (Number1 = 200) { counter = 1; } } } else if (counter == 1) { if (Number2 = 200) { counter = 0; } } } } 

好吧,那么你想要做的是建立一个介于0到200之间的正弦波,但是在什么时期? 你想让它循环每8个电话吗?

怎么样,利用内置的Java Math.sin函数:

 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范围内。

(如果double对你有效,你不必将数字转换为int,我只是遵循你上面所写的精神。)

*更新以产生正弦波**

这应该做你想要的。 第一部分只是将天使输入振荡到正弦函数。

 // Number starts at middle val private int Number1 = -180; // and is shrinking private int direction = -1; public void updateNumber() { // if the number is in the acceptable range, // keep moving in the direction you were going (up or down) if (Number1 < 180 && Number1 > -180) { Number1 = Number1 + (50 * direction); } else { // otherwise, reverse directions direction = direction * -1; // and start heading the other way Number1 = Number1 + (50 * direction); } } 

此部分使用osculating值,并将其输入到Sine函数,然后进行一些计算以适应0200的值。

 for (int i = 0; i < 200; i++){ System.out.println((100 * (Math.sin((Number1* Math.PI)/180.0)))+100); updateNumber(); } 

结果如下:

 0.0 0.38053019082543926 1.5192246987791975 3.4074173710931746 6.03073792140917 9.369221296335013 13.397459621556138 18.084795571100827 23.395555688102192 29.28932188134526 35.72123903134607 42.64235636489539 50.00000000000001 57.738173825930055 65.79798566743312 74.11809548974793 82.63518223330696 91.28442572523419 100.0 108.71557427476581 117.36481776669304 125.88190451025207 134.20201433256688 142.26182617406994 150.0 157.3576436351046 164.27876096865393 170.71067811865476 176.6044443118978 181.9152044288992 186.60254037844385 190.630778703665 193.96926207859082 196.59258262890683 198.4807753012208 199.61946980917457 200.0 

所以你在看不连续的步骤? 正弦/余弦是连续函数,因此如果您尝试以这种方式实现它,您实际上将获得遵循正弦/余弦曲线的阶跃函数。

你每次通过函数递增50,所以你只能在循环之前得到值{1,51,101,151}(我假设counter = 1行应该是Number1 = 1)。

您能否提供更多信息供我们解答?