PHP's log1p in TypeScript

āœ“ Verified: PHP 8.3
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { log1p } from 'locutus/php/math/log1p'.

Or with CommonJS: const { log1p } = require('locutus/php/math/log1p')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

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

Notes

  • Precision ā€˜n’ can be adjusted as desired

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

export function log1p(x: number): number | string {
// discuss at: https://locutus.io/php/log1p/
// parity verified: PHP 8.3
// 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
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP math functions


Star