Python's math.isclose in TypeScript

✓ Verified: Python 3.12
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 { isclose } from 'locutus/python/math/isclose'.

Or with CommonJS: const { isclose } = require('locutus/python/math/isclose')

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
1isclose(0.1 + 0.2, 0.3)true
2isclose(1000.0, 1001.0, 0.01)true
3isclose(1.0, 1.1, 1e-9, 0)false

Notes

  • Tests whether two numbers are close within relative/absolute tolerances.

Here's what our current TypeScript equivalent to Python's math.isclose looks like.

export function isclose(
a: number | string,
b: number | string,
relTol: number | string = 1e-9,
absTol: number | string = 0,
): boolean {
// discuss at: https://locutus.io/python/isclose/
// parity verified: Python 3.12
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Tests whether two numbers are close within relative/absolute tolerances.
// example 1: isclose(0.1 + 0.2, 0.3)
// returns 1: true
// example 2: isclose(1000.0, 1001.0, 0.01)
// returns 2: true
// example 3: isclose(1.0, 1.1, 1e-9, 0)
// returns 3: false

const left = Number(a)
const right = Number(b)
const relative = Number(relTol)
const absolute = Number(absTol)

if (!Number.isFinite(relative) || !Number.isFinite(absolute) || relative < 0 || absolute < 0) {
throw new RangeError('isclose(): tolerances must be non-negative finite numbers')
}

if (Number.isNaN(left) || Number.isNaN(right)) {
return false
}
if (left === right) {
return true
}
if (!Number.isFinite(left) || !Number.isFinite(right)) {
return false
}

const difference = Math.abs(left - right)
const threshold = Math.max(relative * Math.max(Math.abs(left), Math.abs(right)), absolute)
return difference <= threshold
}

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


We have 34 Python functions so far - help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.

« More Python math functions


Star