# How financial_rigor.py Verifies Market Cap with Exact Decimal Precision

> Discover how financial_rigor.py ensures exact market cap verification using Python's Decimal type to avoid floating-point errors. Learn about its precise calculation method.

- Repository: [Xbt Lin/ai-berkshire](https://github.com/xbtlin/ai-berkshire)
- Tags: how-to-guide
- Published: 2026-07-25

---

**financial_rigor.py uses Python's Decimal type with a 28-digit precision context to eliminate floating-point errors when multiplying price by shares, then calculates percentage deviation from the reported market cap to verify accuracy.**

The `ai-berkshire` repository by xbtlin provides institutional-grade financial validation tools for investment research. Its [`financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/financial_rigor.py) module demonstrates how to verify market cap with exact decimal precision, ensuring that calculations involving billions of shares remain mathematically exact and auditor-friendly.

## Converting Inputs to Exact Decimals

The verification process begins by sanitizing all numeric inputs to prevent floating-point contamination from compromising the calculation.

### The exact() Helper Function

Located at [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py) lines 31-38, the `exact()` helper converts floats, integers, and strings into `Decimal` objects. It avoids the binary-float trap by passing the string representation of the value to the Decimal constructor, ensuring that inputs like `9.11e9` are preserved with perfect accuracy rather than being subject to IEEE 754 floating-point approximation.

## Performing Precise Multiplication

Once inputs are converted, the module performs arithmetic within a controlled precision environment that guarantees reproducibility.

### Custom Decimal Context Configuration

The module defines a dedicated `_CTX` context configured with **28-digit precision** and "round-half-even" rounding mode. This context ensures that intermediate calculations maintain arbitrary precision without floating-point drift, which is critical when dealing with large-cap equities valued in the trillions.

### The Multiplication Operation

At line 67 in [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py), the script executes `_CTX.multiply(p, s)` where `p` represents price and `s` represents shares. Using the context's `multiply` method rather than standard operators guarantees that the result adheres strictly to the configured 28-digit precision boundary, eliminating the typical 1-2 unit-in-last-place errors common in binary float arithmetic.

## Calculating and Validating Deviation

After computing the theoretical market cap, the module validates it against reported figures using exact decimal arithmetic.

The reported market cap is also converted to a `Decimal` using the same `exact()` helper. The deviation percentage is calculated as `abs(calculated - reported) / reported * 100` (lines 68-78). Because both operands are Decimal objects, the percentage calculation remains free of floating-point artifacts.

The `verify_market_cap()` function returns a Boolean indicating whether the deviation falls within the acceptable **5% threshold**. If the deviation exceeds this limit, the function flags a warning, prompting analysts to verify share counts, price freshness, and currency units. The accompanying `fmt_number()` helper formats large values (billions, trillions) for human-readable output while preserving the underlying exact Decimal values.

## Usage Examples

### Command-Line Verification

You can verify market cap directly from the terminal using the script's CLI interface:

```bash
python3 tools/financial_rigor.py verify-market-cap \
    --price 510 \
    --shares 9.11e9 \
    --reported 4.65e12 \
    --currency HKD

```

### Programmatic Integration

For integration into analysis pipelines, import the verification function directly:

```python
from tools.financial_rigor import verify_market_cap

# Inputs can be floats, ints, strings, or Decimals

price = 510                # HKD per share

shares = 9.11e9            # total shares outstanding

reported_cap = 4.65e12     # reported market capitalization

# Returns True if deviation ≤ 5%

is_valid = verify_market_cap(price, shares, reported_cap, currency="HKD")
print("Market cap check passed?", is_valid)

```

## Summary

- **Exact decimal conversion**: The `exact()` helper at lines 31-38 converts all inputs to Decimal via string representation, avoiding binary float contamination.
- **Precision-controlled arithmetic**: A dedicated `_CTX` context with 28-digit precision handles multiplication at line 67, eliminating rounding errors in billion-share calculations.
- **Deterministic validation**: Deviation calculation at lines 68-78 uses pure Decimal arithmetic to compute percentage differences, flagging variances greater than 5%.
- **Audit-ready output**: The combination of exact arithmetic and formatted reporting ensures reproducible, transparent market cap verification suitable for institutional research workflows.

## Frequently Asked Questions

### Why does financial_rigor.py use Decimal instead of float for market cap verification?

Standard binary floating-point arithmetic introduces rounding errors that compound when multiplying large share counts (billions) by share prices. Python's Decimal type provides arbitrary-precision arithmetic, ensuring that calculations remain exact to the specified number of decimal places and eliminating the 1-2 unit-in-last-place errors inherent in IEEE 754 float operations.

### What precision level does the Decimal context use in financial_rigor.py?

The module configures a custom context `_CTX` with 28-digit precision and round-half-even rounding mode. This provides sufficient precision to handle large-cap equities valued in trillions while maintaining deterministic, reproducible results across multiple calculation runs.

### How does the script handle different input types like floats and scientific notation?

The `exact()` helper function accepts floats, integers, strings, or existing Decimal objects. It converts inputs by passing their string representation to the Decimal constructor, which correctly handles scientific notation (e.g., `9.11e9`) without introducing the precision loss that would occur from floating-point intermediate conversion.

### What deviation threshold is considered acceptable in the market cap verification?

The `verify_market_cap()` function applies a 5% deviation threshold. If the absolute percentage difference between the calculated market cap (price × shares) and the reported market cap exceeds 5%, the function returns False and triggers a warning, indicating potential data inconsistencies in share counts, pricing, or currency conversions.