Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

question from:https://stackoverflow.com/questions/66057998/how-do-i-make-this-function-more-precise

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
142 views
Welcome To Ask or Share your Answers For Others

1 Answer

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...