JavaScript log1p
Returns log(1 + number), computed in a way that accurate even when the value of number is close to zero
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 | function log1p (x) { // Returns log(1 + number), computed in a way that accurate even when the value of number is close to zero // // version: 1109.2015 // discuss at: http://phpjs.org/functions/log1p // + original by: Brett Zamir (http://brett-zamir.me) // % note 1: Precision 'n' can be adjusted as desired // * example 1: log1p(1e-15); // * returns 1: 9.999999999999995e-16 var ret = 0, n = 50; // degree of precision if (x <= -1) { return '-INF'; // JavaScript style would be to return Number.NEGATIVE_INFINITY } if (x < 0 || x > 1) { return Math.log(1 + x); } for (var i = 1; i < n; i++) { if ((i % 2) === 0) { ret -= Math.pow(x, i) / i; } else { ret += Math.pow(x, i) / i; } } return ret;} |
Examples
Running
1 | log1p(1e-15); |
Should return
1 | 9.999999999999995e-16 |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have log1p goodness in JavaScript.
No comments yet. Be the first!
spread the word:
Use any PHP function in JavaScript
These kind folks have already donated: AYHAN BARI*, Nikita Ekshiyan, Nikita Ekshiyan, Petr Pavel, @HalfWinter, Paulo Freitas, Andros Peña Romo, @andorosu, Raimund Szabo, Nitin Gupta, @nikosdion, Anonymous, Anonymous and Shawn Houser.
<your name here>