Java:与Karplus Strong方程相关的方程的方法不会返回预期结果;原因不明



在提示的第1部分中,我将把一个等式集成到Java中,以获得句点(T)的值。方程式如下:T=FS/(440*(2^(h/12))

注:

FS=采样率,为44100/1。

h=半步,由用户提供。

这个方程的一个例子是:44100/(440*(2^(2/12))=89.3

我写的代码如下:

public static double getPeriod(int halfstep) {
double T = 100; // TODO: Update this based on note

double FS = 44100 / 1;
double power = Math.pow(2, (halfstep / 12));
double denominator = 440 * (power);
double result = (FS) / (denominator);
T = Math.round(result);

return T;
}
// Equation test.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("halfstep is: ");
int halfstep = in.nextInt();

double period = getPeriod(halfstep);
System.out.print("Period: " + period + " ");
}

但是,当我运行这个代码时,h=2,T=100.0,而不是预期的89.3,我不确定问题是什么。有什么想法吗?

因为halfStepint,所以在编写时

(halfstep / 12)

通过取CCD_ 3并四舍五入到最接近的整数来进行计算。因此,如果在这里插入2,那么halfStep / 12将返回为0,而不是1/6。这会打乱计算,很可能是给你错误答案的原因。

关于如何在这里继续,您有几个选项。一种是将halfStep改变为double而不是int。另一个是将该部门改写为

halfStep / 12.0

由于12.0是一个double文字,它将按照您想要的方式执行除法。

另一个潜在问题是,您将变量T声明为100.0,但在计算中的任何位置都不要使用T,并在返回之前最终覆盖它。我不确定这是故意的,还是表明其中一个公式不正确。

希望这能有所帮助!

最新更新