Okay, my assignment is to produce an array values a sine wave with a custom frequency. This is my sine function:
好的,我的任务是生成一个具有自定义频率的正弦波的数组值。这是我的正弦函数:
Math.sin(frequency*(j/samplesPerSecond)*Math.PI*2)
j
is the array index and samplesPerSecond
equals 44100.
j是数组索引,samplesPerSecond等于44100。
Now for an array of 100,000 values it returns 0.0 for the first 33,000, 1.571509...E-14 for the next 33,000 and 3.143018...E-14 for the rest.
现在,对于100,000个值的数组,它返回0.0为前33,000,1.571509 ... E-14为下一个33,000和3.143018 ... E-14为其余。
I've tried System.out.println(Math.sin(Math.PI));
and it doesn't return 0 but it returns 1.224646...E-16
我试过System.out.println(Math.sin(Math.PI));并且它不返回0但它返回1.224646 ... E-16
This is my first java assignment so I might be overlooking something really obvious here, but I'm really confused.
这是我的第一个java任务,所以我可能会忽略一些非常明显的东西,但我真的很困惑。
3 个解决方案
#1
4
Try changing to this:
尝试更改为:
Math.sin(1.0 * frequency*(1.0 * j / samplesPerSecond) * Math.PI * 2)
See if it works better.
看看它是否更好。
I suspect you have issue with integer division.
我怀疑你有整数除法的问题。
In Java 2/5 = 0, you know, while 1.0 * 2 / 5
is what you would expect usually ( 0.4 ).
在Java 2/5 = 0中,您知道,而1.0 * 2/5通常是您所期望的(0.4)。
#2
2
Most probably you are dealing with integer division. So if the numerator is less than denominator it will round to zero. Try converting/casting j or samplesPerSecond to float or double.
很可能你正在处理整数除法。因此,如果分子小于分母,它将舍入为零。尝试将j或samplesPerSecond转换/转换为float或double。
#3
1
j
is the array index andsamplesPerSecond
equals 44100.j是数组索引,samplesPerSecond等于44100。
As an array index, I assume j
is of type int
. This is your primary issue, as you're performing integer division, which truncates the result to a whole number. Either cast j
to a double
, or multiply it by a double before dividing:
作为数组索引,我假设j是int类型。这是您的主要问题,因为您正在执行整数除法,它会将结果截断为整数。将j转换为double,或者在除以之前将其乘以double:
((double)j / samplesPerSecond)
(1.0 * j / samplesPerSecond)
#1
4
Try changing to this:
尝试更改为:
Math.sin(1.0 * frequency*(1.0 * j / samplesPerSecond) * Math.PI * 2)
See if it works better.
看看它是否更好。
I suspect you have issue with integer division.
我怀疑你有整数除法的问题。
In Java 2/5 = 0, you know, while 1.0 * 2 / 5
is what you would expect usually ( 0.4 ).
在Java 2/5 = 0中,您知道,而1.0 * 2/5通常是您所期望的(0.4)。
#2
2
Most probably you are dealing with integer division. So if the numerator is less than denominator it will round to zero. Try converting/casting j or samplesPerSecond to float or double.
很可能你正在处理整数除法。因此,如果分子小于分母,它将舍入为零。尝试将j或samplesPerSecond转换/转换为float或double。
#3
1
j
is the array index andsamplesPerSecond
equals 44100.j是数组索引,samplesPerSecond等于44100。
As an array index, I assume j
is of type int
. This is your primary issue, as you're performing integer division, which truncates the result to a whole number. Either cast j
to a double
, or multiply it by a double before dividing:
作为数组索引,我假设j是int类型。这是您的主要问题,因为您正在执行整数除法,它会将结果截断为整数。将j转换为double,或者在除以之前将其乘以double:
((double)j / samplesPerSecond)
(1.0 * j / samplesPerSecond)