PHP's log1p in JavaScript

How to use

You you can install via yarn add locutus and require this function via const log1p = require('locutus/php/math/log1p').

It is important to use a bundler that supports tree-shaking so that you only ship the functions that you actually use to your browser, instead of all of Locutus, which is massive. Examples are: Parcel, webpack, or rollup.js. For server-side use this is typically less of a concern.

Examples

Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.

#codeexpected result
1log1p(1e-15)9.999999999999995e-16

Notes

  • Precision ‘n’ can be adjusted as desired

Here’s what our current JavaScript equivalent to PHP's log1p looks like.

module.exports = function log1p(x) {
// discuss at: https://locutus.io/php/log1p/
// original by: Brett Zamir (https://brett-zamir.me)
// improved by: Robert Eisele (https://www.xarg.org/)
// note 1: Precision 'n' can be adjusted as desired
// example 1: log1p(1e-15)
// returns 1: 9.999999999999995e-16

let ret = 0
// degree of precision
const n = 50

if (x <= -1) {
// JavaScript style would be to return Number.NEGATIVE_INFINITY
return '-INF'
}
if (x < 0 || x > 1) {
return Math.log(1 + x)
}
for (let i = 1; i < n; i++) {
ret += Math.pow(-x, i) / i
}

return -ret
}

A community effort

Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we assimilate first iterations with imperfections, hoping for others to take issue with-and improve them. This unorthodox approach has worked very well to foster fun and fruitful collaboration, but please be reminded to use our creations at your own risk. THE SOFTWARE IS PROVIDED "AS IS" has never been more true than for Locutus.

Now go and: [ View on GitHub | Edit on GitHub | View Raw ]


« More PHP math functions


Star