Metadata-Version: 2.4
Name: arpfloat
Version: 0.1.12
License-File: LICENSE
Summary: Arbitrary-precision floating point library
Author-email: Nadav Rotem <nadav256@gmail.com>
Requires-Python: >=3.6
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Homepage, https://github.com/akkaze/arpfloat
Project-URL: Repository, https://github.com/akkaze/arpfloat

# ARPFloat – Arbitrary-Precision Floating-Point Library

[![Latest Version]][crates.io] [![Docs Badge]][docs]

[Latest Version]: https://img.shields.io/crates/v/arpfloat.svg
[crates.io]: https://crates.io/crates/arpfloat
[Docs Badge]: https://docs.rs/arpfloat/badge.svg
[docs]: https://docs.rs/arpfloat

---

## English Version

ARPFloat is a high‑precision floating‑point library written in **Rust** with **first‑class Python bindings**.  
It lets you emulate existing formats (FP16, FP32, FP128, BF16, …) and define **custom** floating‑point types with arbitrary exponent/precision sizes.  
Rounding modes are part of the type system, ensuring deterministic and reproducible numerical behaviour – perfect for **deep learning quantization**, numerical simulations, and embedded systems.

### 🚀 Python Bindings – Get Started in Seconds

Install the Python package via **pip**:

```bash
pip install arpfloat
```

Then you can immediately experiment with floating‑point formats:

```python
from arpfloat import Float, Semantics, FP16, BF16, FP32, fp64, pi

# Convert and compute in FP16
x = fp64(2.5).cast(FP16)
y = fp64(1.5).cast(FP16)
print(x + y)          # 4.0

# Define a custom format (e.g., FP8 with 4 exponent bits, 3 mantissa bits + hidden)
FP8 = Semantics(4, 4, "NearestTiesToEven")
a = fp64(0.7).cast(FP8)
b = fp64(0.2).cast(FP8)
c = a.cast(FP32) + b.cast(FP32)   # promote to avoid low‑precision accumulation
print(c)              # 0.875 (rounded according to FP8 rules)

# High‑precision constants
print(pi(FP32))       # 3.1415927
print(pi(FP16))       # 3.140625
```

#### Why ARPFloat for Python Users?

- **Validate quantization algorithms** – simulate FP8, FP4, or any exotic format directly in Python.
- **Saturating arithmetic** – overflow clamps to the maximum/minimum finite value instead of producing `inf` (by choosing the appropriate rounding mode and format bounds). This is crucial for safe inference in quantized neural networks.
- **Drop‑in compatible** – seamlessly integrate with NumPy arrays and your existing Python ML pipeline.
- **Reproducible rounding** – every operation respects the explicitly specified rounding mode, avoiding global state pollution (no `fenv.h` surprises).

#### Python Example: FP8 Dot Product

```python
import numpy as np
from arpfloat import FP32, fp64, Semantics

FP8 = Semantics(4, 4, "NearestTiesToEven")   # 4 exponent bits, 3 mantissa bits + hidden

A = np.random.rand(1000000)
B = np.random.rand(1000000)
ref = np.dot(A, B)   # reference in fp64

A8 = [fp64(x).cast(FP8) for x in A]
B8 = [fp64(x).cast(FP8) for x in B]
dot = sum([a.cast(FP32) * b.cast(FP32) for a, b in zip(A8, B8)])
print("FP8 quantized dot product:", dot)
print("Reference (fp64):", ref)
```

### 📦 Installation

#### Rust (Cargo)
```toml
[dependencies]
arpfloat = "0.8"
```

#### Python (pip)
```bash
pip install arpfloat
```
(Pre‑built wheels are available for most platforms.)

### 🧠 Key Features

| Feature | Description |
|---------|-------------|
| **Custom semantics** | Define any floating‑point format (exponent bits, mantissa bits, rounding mode). |
| **Rounding modes** | `NearestTiesToEven`, `Zero`, `Up`, `Down`, `Away` – statically enforced. |
| **Saturating arithmetic** | Overflow clamps to finite limits (e.g., for safe quantization). |
| **High‑precision functions** | `exp`, `log`, `sqrt`, `pow`, trigonometric, `pi`, `e`, etc. |
| **Inspecting internals** | View mantissa, exponent, sign bits – perfect for debugging. |
| **Continued fractions** | Approximate any float as a rational `p/q`. |
| **`no_std` support** | Disable default `std` feature for embedded environments. |

### 🔬 Low‑level Rust Example

```rust
use arpfloat::{Float, FP128};

let n = Float::from_f64(5.).cast(FP128);
let mut x = n.clone();
for _ in 0..20 {
    x += (&n / &x) / 2;
}
println!("sqrt(5) = {}", x);  // 2.2360679774997896964091736687312763
```

### 📚 References

Built upon classic works:
- *Handbook of Floating‑Point Arithmetic* (Muller et al.)
- *Elementary Functions* (Muller)
- *Modern Computer Arithmetic* (Brent & Zimmermann)
- Papers by Gal & Bachelis, Steele & White, Goldberg, etc.

### 📄 License

Apache‑2.0

---

## 中文版本

ARPFloat 是一个用 **Rust** 编写的高精度浮点库，并提供**一流的 Python 绑定**。  
它支持模拟现有浮点格式（FP16、FP32、FP128、BF16 等），并允许定义**自定义**浮点类型（任意指数位宽和精度）。  
舍入模式被纳入类型系统，保证了确定且可复现的数值行为——非常适合**深度学习量化**、数值模拟和嵌入式系统。

### 🚀 Python 绑定 – 秒级上手

通过 **pip** 安装 Python 包：

```bash
pip install arpfloat
```

然后即可开始使用：

```python
from arpfloat import Float, Semantics, FP16, BF16, FP32, fp64, pi

# 转换为 FP16 并计算
x = fp64(2.5).cast(FP16)
y = fp64(1.5).cast(FP16)
print(x + y)          # 4.0

# 定义自定义格式（例如 FP8：4 位指数，3 位尾数 + 隐含位）
FP8 = Semantics(4, 4, "NearestTiesToEven")
a = fp64(0.7).cast(FP8)
b = fp64(0.2).cast(FP8)
c = a.cast(FP32) + b.cast(FP32)   # 提升精度以避免低精度累加误差
print(c)              # 0.875（按 FP8 舍入规则）

# 高精度常数
print(pi(FP32))       # 3.1415927
print(pi(FP16))       # 3.140625
```

#### 为何 Python 用户应选择 ARPFloat？

- **验证量化算法** – 直接在 Python 中模拟 FP8、FP4 或任何其他格式。
- **饱和运算** – 溢出时钳位到最大/最小有限值，而非产生 `inf`（通过选择合适的舍入模式和格式边界）。这对量化神经网络的安全推理至关重要。
- **即插即用** – 与 NumPy 数组及现有 Python ML 流程无缝集成。
- **可重现的舍入** – 每次运算都遵循显式指定的舍入模式，避免全局状态污染（无 `fenv.h` 副作用）。

#### Python 示例：FP8 点积

```python
import numpy as np
from arpfloat import FP32, fp64, Semantics

FP8 = Semantics(4, 4, "NearestTiesToEven")   # 4 位指数，3 位尾数 + 隐含位

A = np.random.rand(1000000)
B = np.random.rand(1000000)
ref = np.dot(A, B)   # 双精度参考值

A8 = [fp64(x).cast(FP8) for x in A]
B8 = [fp64(x).cast(FP8) for x in B]
dot = sum([a.cast(FP32) * b.cast(FP32) for a, b in zip(A8, B8)])
print("FP8 量化点积结果:", dot)
print("双精度参考值:", ref)
```

### 📦 安装

#### Rust（Cargo）
```toml
[dependencies]
arpfloat = "0.8"
```

#### Python（pip）
```bash
pip install arpfloat
```
（已为大部分平台提供预编译 wheel。）

### 🧠 核心特性

| 特性 | 描述 |
|------|------|
| **自定义语义** | 定义任意浮点格式（指数位宽、尾数位宽、舍入模式）。 |
| **舍入模式** | `NearestTiesToEven`、`Zero`、`Up`、`Down`、`Away` – 静态强制。 |
| **饱和运算** | 溢出时钳位至有限边界（例如用于安全量化）。 |
| **高精度函数** | `exp`、`log`、`sqrt`、`pow`、三角函数、`pi`、`e` 等。 |
| **内部探查** | 查看尾数、指数、符号位 – 便于调试。 |
| **连分数** | 将任意浮点数近似为有理数 `p/q`。 |
| **`no_std` 支持** | 禁用默认 `std` 特性，可用于嵌入式环境。 |

### 🔬 底层 Rust 示例

```rust
use arpfloat::{Float, FP128};

let n = Float::from_f64(5.).cast(FP128);
let mut x = n.clone();
for _ in 0..20 {
    x += (&n / &x) / 2;
}
println!("sqrt(5) = {}", x);  // 2.2360679774997896964091736687312763
```

### 📚 参考

实现参考经典著作：
- 《Handbook of Floating‑Point Arithmetic》（Muller 等）
- 《Elementary Functions》（Muller）
- 《Modern Computer Arithmetic》（Brent & Zimmermann）
- Gal & Bachelis、Steele & White、Goldberg 等的论文

### 📄 许可证

Apache‑2.0

