btebsv
btebsv

Reputation: 1

Java: method for an equation relevant to the Karplus-Strong equation does not return the anticipated result; unclear cause

In Part 1 of a prompt, I am expected to integrate an equation into Java to get the value for a period (T). The equation is as follows: T = FS / (440 * (2 ^(h/12))

NOTE:

FS = sample rate, which is 44100 / 1.

h = halfstep, which is provided by the user.

An example of this equation is: 44100 / (440 * (2 ^(2/12)) = 89.3

The code I wrote is as follows:

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 + " ");
}

But when I run through this code with h = 2, T = 100.0 instead of the anticipated 89.3 and I am not sure what the issue is. Any thoughts on what's going on?

Upvotes: 0

Views: 33

Answers (1)

templatetypedef
templatetypedef

Reputation: 372814

Because halfStep is an int, when you write

(halfstep / 12)

the calculation is done by taking halfStep / 12 and rounding down to the nearest integer. As a result, if you plug in 2 here, then halfStep / 12 will come back as 0 instead of 1/6. That's messing up the computation and is likely what's giving you the wrong answer.

You have a few options for how to proceed here. One would be to change halfStep to be a double rather than an int. Another would be to rewrite the division as

halfStep / 12.0

which, since 12.0 is a double literal, will perform the division in the way you intend.

One other potential issue - you declare the variable T as 100.0, but never use T anywhere in the calculation and ultimately overwrite it before returning it. I'm not sure whether this is intentional or whether that indicates that one of the formulas is incorrect.

Hope this helps!

Upvotes: 0

Related Questions