Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Power operations improvements #1

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 31 additions & 7 deletions src/Quantity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -477,16 +477,40 @@ export default class Quantity {
}

/**
* Raise one quantity to the power of an integer. This can cause precision loss
* Raise one quantity to the power of another. This can cause precision loss
* @param x Quantity to raise
* @param y Exponent
* @returns Result of the power operation
*/
static __pow(x: Quantity, y: number) {
if (!Number.isInteger(y)) {
throw new Error("Cannot raise Quantity to the power of a non-integer number");
static __pow(x: Quantity, y: Quantity | bigint) {
if (typeof y !== "bigint" && !Quantity.isQuantity(y)) {
throw new Error("Invalid exponent");
}
if (y === 0) return new Quantity(0, x.#D);

// power of 0
if ((typeof y === "bigint" && y === 0n) || Quantity.isQuantity(y) && Quantity.eq(y, new Quantity(0n, y.#D))) {
return Quantity.__one(x.#D);
}

// integer power
if (typeof y === "bigint") {
const positivePower = new Quantity(
x.#qty ** (y > 0 ? y : -y),
x.#D ** y
)._convert(x.#D);

// negative exponent
if (y > 0) return positivePower;

// calculate negative exponent
const result = Quantity.__one(x.#D);
result._div(positivePower);

return result;
}

// ensure same denomination
[x, y] = Quantity.sameDenomination(x, y);

let res = x.clone();

Expand All @@ -506,11 +530,11 @@ export default class Quantity {
}

/**
* Raise one quantity to the power of an integer (in-place). This can cause
* Raise one quantity to the power of another (in-place). This can cause
* precision loss
* @param y Exponent
*/
_pow(y: number) {
_pow(y: Quantity | bigint) {
const res = Quantity.__convert(
Quantity.__pow(this, y),
this.#D
Expand Down
Loading