How do I make this function more precise?

Viewed 69

I'm a beginner and I made a function to calculate the length of a semi-circular infinite snake figure. I took in two arguments; one of the radius the initial circle, and the next to be the precision (which is just the number of semi-circles).

Here's a diagram of the snake I'm talking about.

Here's what I wrote:

function snake(radius, precision) {
    var pi = 3.14159265359
    var exp = 1 - precision; 
    var sub = Math.pow(2, exp);
    var product = 2 - sub;
    var length = pi * radius * product
        return length
}

I'm noticing that at one point the precision doesn't matter when I go really high as the value it return is the same. Is there a way to make it more precise?

3 Answers

You may use the constant Math.PI instead of your pi variable.

Feels like Number.toPrecision() is what you are looking for. Below is slightly cleaned up version of your code snippet. For the return value I'm using length.toPrecision(50):

function snake(radius, precision) {
    const exp = 1 - precision; 
    const sub = Math.pow(2, exp);
    const product = 2 - sub;
    const length = Math.PI * radius * product;
    return length.toPrecision(50);
}

console.log(snake(5, 55));

Yo can find out more about toPrecision() here. The max precision value is 100.

This will be my method,

Length can be get by sum of the below series according to the screen shot,

PI X R (1 + 1/2 + 1/4 + ...)

S(n) = PIxR(1-0.5^n)/(1-0.5)

So the JavaScript function is,

function length(r, n) {
 const ln = Math.PI * r * (1 - Math.pow(0.5, n))/(1 - 0.5);
 return ln.toPrecision(50);
}
Related