> For the complete documentation index, see [llms.txt](https://docs.pretoke.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.pretoke.xyz/smart-contracts/fixed-point-math.md).

# Fixed-Point Math Library

> **Contract version:** v0.1.0 | **Acton CLI:** 1.1.0 | **Source:** `contracts/src/fixed_math.tolk`

This document describes the Q64.64 fixed-point math library used by the LmsrMarketMaker contract for LMSR pricing calculations. All intermediate arithmetic in cost function evaluation, marginal price computation, and trade net-cost calculations is performed in this fixed-point format.

***

## Q64.64 Representation

Q64.64 is a signed fixed-point number format that uses a 257-bit TVM integer to store values with 64 integer bits and 64 fractional bits.

* **Integer bits:** 64 (upper portion after sign)
* **Fractional bits:** 64 (lower portion)
* **Unit constant (ONE):** 2^64 = `18446744073709551616`

A Q64.64 value `v` represents the real number `v / ONE = v / 2^64`.

### Representable Value Range

| Property               | Value                                             |
| ---------------------- | ------------------------------------------------- |
| Minimum positive value | 1 (represents 2^-64 ≈ 5.42 × 10^-20)              |
| Maximum positive value | Limited by TVM integer precision (257-bit signed) |
| Smallest magnitude     | 2^-64 ≈ 5.421 × 10^-20                            |
| Resolution (ULP)       | 2^-64 ≈ 5.421 × 10^-20                            |
| ONE                    | 18446744073709551616 (represents 1.0)             |
| 2 × ONE                | 36893488147419103232 (represents 2.0)             |

***

## Constants

### LOG2\_E — Binary Logarithm of Euler's Number

* Mathematical definition: log₂(e) ≈ 1.4426950408889634
* Q64.64 encoded value: `26613026195688644984`
* Used in Step 1 of `lmsrCost` — converting natural-scale quantities to log2-space: `log2_scaled[i] = q_i * LOG2_E / funding`.

### LN\_2 — Natural Logarithm of 2

* Mathematical definition: ln(2) ≈ 0.6931471805599453
* Q64.64 encoded value: `12786308645202655660`
* Used in Step 5 of `lmsrCost` — converting log2 back to natural log: `lnSum = (totalLog2 * LN_2) >> 64`. Also used in `fixed_ln`: `ln(x) = log2(x) × ln(2)`.

### EXP\_LIMIT — Maximum Safe Exponent for pow2

* Mathematical definition: \~3.4 × ONE (maximum safe 2^x argument before overflow risk)
* Q64.64 encoded value: `62771017353866807638`
* Used in Step 3 of `lmsrCost` — when the max log2-scaled value exceeds EXP\_LIMIT, all exponent arguments are reduced by `(max − EXP_LIMIT)` to prevent `fixed_pow2` overflow.

***

## Function Reference

### fixed\_mul(a, b) → int

`fun fixed_mul(a: int, b: int): int` — computes `(a * b) >> 64`. Approximation error ≤ 1 ULP due to truncation.

### fixed\_div(a, b) → int

`fun fixed_div(a: int, b: int): int` — computes `(a << 64) / b`. Throws `400` if `b == 0`.

### fixed\_log2(x) → int

`fun fixed_log2(x: int): int` — returns log₂(x). Input domain `x > 0`; throws `401` if `x ≤ 0`. Algorithm: normalize `x` into `[ONE, 2×ONE)` counting shifts as the integer part, then 64 iterations of squaring for the fractional part.

### fixed\_pow2(x) → int

`fun fixed_pow2(x: int): int` — returns 2^x, handling negative exponents. Splits `x` into integer + fractional parts; fractional part uses a 9-term Taylor series (see below); combines via left-shift by the integer part; inverts (`(ONE << 64) / result`) if the original exponent was negative.

### fixed\_ln(x) → int

`fun fixed_ln(x: int): int` — returns ln(x) via `fixed_mul(fixed_log2(x), LN_2)`. Throws `401` if `x ≤ 0` (propagated from `fixed_log2`).

### fixed\_exp(x) → int

`fun fixed_exp(x: int): int` — returns e^x via `fixed_pow2(fixed_mul(x, LOG2_E))`.

### fixed\_max(arr) → int

`fun fixed_max(arr: cell): int` — returns the maximum value from a cell storing count (uint32) followed by count int257 values. Throws `402` if count == 0.

***

## Taylor Series Approximation (fixed\_pow2)

The `fixed_pow2` function uses a 9-term Taylor/Maclaurin series to approximate `2^f` for the fractional part `f ∈ [0, 1)`, based on the expansion `2^f = e^(f × ln(2)) = Σ (f × ln(2))^k / k!`.

### Coefficients

| Coefficient | Formula      | Q64.64 Value           | Approximate Real Value |
| ----------- | ------------ | ---------------------- | ---------------------- |
| c1          | ln(2)^1 / 1! | `12786308645202655660` | 0.693147180559945      |
| c2          | ln(2)^2 / 2! | `4431396893595737425`  | 0.240226506959101      |
| c3          | ln(2)^3 / 3! | `1023870087579328453`  | 0.055504108664822      |
| c4          | ln(2)^4 / 4! | `177423166116318949`   | 0.009618129107629      |
| c5          | ln(2)^5 / 5! | `24596073471909060`    | 0.001333355814497      |
| c6          | ln(2)^6 / 6! | `2841449829983171`     | 0.000154035303933      |
| c7          | ln(2)^7 / 7! | `281363276907910`      | 0.000015252733804      |
| c8          | ln(2)^8 / 8! | `24378270262728`       | 0.000001321543920      |
| c9          | ln(2)^9 / 9! | `1877525477726`        | 0.000000101780860      |

(c1 equals `LN_2` since ln(2)^1 / 1! = ln(2).)

### Horner's Method Evaluation Order

```
2^f = ONE + f × (c1 + f × (c2 + f × (c3 + f × (c4 + f × (c5 + f × (c6 + f × (c7 + f × (c8 + f × c9))))))))
```

Evaluated from the innermost coefficient (c9) outward, each step multiplying the accumulator by the fractional part (`>> 64` normalization) and adding the next coefficient — this ordering keeps numerical error small by accumulating the smallest terms first.

### Precision

The 9-term approximation provides relative error < 10^-18 for the fractional part, well within 1 ULP. The dominant error source is truncation from each `>> 64` shift (up to 9 × 1 ULP accumulated).

***

## Error Codes

| Code | Trigger Condition                  | Function                 |
| ---- | ---------------------------------- | ------------------------ |
| 400  | `b == 0` in `fixed_div(a, b)`      | `fixed_div`              |
| 401  | `x ≤ 0` in logarithm functions     | `fixed_log2`, `fixed_ln` |
| 402  | `count == 0` in cell-encoded array | `fixed_max`              |

All domain violations use the Tolk `assert(...) throw <code>` pattern — the transaction aborts with the specified exit code and no state changes persist.

***

## Overflow Prevention Technique

The LMSR cost function `C(q) = b × ln(Σ exp(q_i / b))` can overflow intermediate `exp()` values when position balances grow large relative to funding. The `lmsrCost` function solves this with a **log2-space offset method**:

1. **Log2-scale:** `log2_scaled[i] = q_i × LOG2_E / funding` (converts `exp(q_i/b)` into `pow2(log2_scaled[i])`)
2. **Find max:** `maxLog2Scaled = max(log2_scaled[...])`
3. **Compute offset:** if `maxLog2Scaled > EXP_LIMIT`, `offset = maxLog2Scaled − EXP_LIMIT`, else `0`
4. **Sum offset-adjusted exponentials:** `sumExp = Σ pow2(log2_scaled[i] − offset)` — every argument is now ≤ EXP\_LIMIT
5. **Recombine:** `log2Sum = fixed_log2(sumExp)`, `totalLog2 = log2Sum + offset`, `lnSum = (totalLog2 × LN_2) >> 64`, `cost = lnSum × funding`

This is mathematically valid because `log₂(Σ 2^(x_i − offset)) + offset = log₂(Σ 2^x_i)`.

`EXP_LIMIT ≈ 3.4 × ONE` means `pow2(EXP_LIMIT) ≈ 10.6 × ONE` — a conservative bound that keeps individual `pow2` results and their summation well within Q64.64 precision. The `calcMarginalPrice` get-method uses the same offset technique; since numerator and denominator share the offset, it cancels out in the division.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.pretoke.xyz/smart-contracts/fixed-point-math.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
