Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

javascript - How do I make this function more precise?

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...