Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/cshaa/arithmetic-types
Interfaces for mathematical data-types to implement
https://github.com/cshaa/arithmetic-types
Last synced: about 2 months ago
JSON representation
Interfaces for mathematical data-types to implement
- Host: GitHub
- URL: https://github.com/cshaa/arithmetic-types
- Owner: cshaa
- License: cc0-1.0
- Created: 2021-05-12T12:09:58.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2021-06-08T01:38:11.000Z (over 3 years ago)
- Last Synced: 2024-10-13T19:38:15.535Z (3 months ago)
- Language: TypeScript
- Size: 44.9 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Arithmetic Types
Standardized interfaces for mathematical data types, such as Complex, Fraction and Matrix.
**This repository is a draft, the standard has not been adopted anywhere yet.**# Overview
* Every implementation of an _Arithmetic Types_ interface **must** provide an `Arithmetics` object with static methods such as `add(x, y)` which accept arguments of a single data type and perform arithmetic operations on it.
* The available interfaces are in [`scalar-arithmetic.ts`](https://github.com/m93a/arithmetic-types/blob/main/lib/scalar-arithmetic.ts) and [`tensor-arithmetic.ts`](https://github.com/m93a/arithmetic-types/blob/main/lib/tensor-arithmetic.ts).
* The methods of `Arithmetics` **must** treat the arguments as immutable and return a new instance where applicable.
* Every instance of the data type **must** provide a `x.clone()` method and a reference to the `Arithmetics` object using `x[Symbol.for('arithmetics')]`.# Example usage
## Static methods
This is how one can implement an arithmetic and geometric mean for fractions, decimals, complex numbers and quaternions etc., regardless of their implementation.
```typescript
import { NormedDivisionRing, InstanceOf, symbols } from 'arithmetic-types'const { Arithmetics } = symbols
type Numeric = InstanceOf< NormedDivisionRing >function arithmeticMean(first: Numeric, ...args: Numeric[])
{
const arithmetics = first[Arithmetics]const sum = args.reduce( (a, b) => arithmetics.add(a, b), first )
const count = args.length + 1return arithmetics.scale(sum, 1/count)
}function geometricMean(first: Numeric, ...args: Numeric[])
{
const arithmetics = first[Arithmetics]
if (!arithmetics.isCommutative) throw new TypeError('Geometric mean of non-commutative numbers is not supported.')const product = args.reduce( (a, b) => arithmetics.mul(a, b), first )
const count = args.length + 1return arithmetics.pow(product, 1/count)
}
```