Metadata-Version: 2.4
Name: hypermath-Kavyansh-Arya
Version: 0.5.2
Summary: A growing Python math library featuring reusable class-based operations for game development, number theory and advanced mathematics.
Author: Kavyansh N Arya
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# HyperMath

### A Growing Python Library for Mathematics, Numerical Computing, and Game Development

HyperMath is a Python mathematical library designed to make mathematical operations more accessible through reusable functions and a consistent class-based API.

Instead of repeatedly implementing mathematical algorithms in every project, developers can use HyperMath to organize and reuse mathematical logic.

The library is intended for:

- 🎮 Game development and simulation
- 📐 Geometry and 3D mathematics
- 🔢 Number theory and advanced calculations
- 📊 Numerical analysis and interpolation
- 🎵 Signal processing and mathematical experimentation
- 🧮 Educational projects and algorithm development

HyperMath is under active development, with new functions and improvements planned across future releases.

---

## Installation

Install HyperMath from PyPI:

```bash
python -m pip install hypermath-Kavyansh-Arya
```

Import the library:

```python
import HyperMath as hm
```

**Note:** The package name used by pip and the Python import name are different. Install `hypermath-Kavyansh-Arya`, then import `HyperMath`.

## Basic Usage

HyperMath uses a class-based API for many operations.

A typical calculation follows this pattern:

```python
import HyperMath as hm

result = hm.factorial(5).calculate()

print(result)
# 120
```

The exact constructor arguments depend on the function being used.

---

# Advanced Mathematical Functions

The following sections describe ten proposed functions that extend HyperMath into numerical analysis, computational geometry, complex mathematics, probability, and game development.

**Availability:** These functions should be marked as planned until their implementations have been added to the published package.

---

## 1. `newton_raphson` — Numerical Root Finding

### Overview

The Newton–Raphson method is an iterative numerical algorithm used to approximate a root of an equation.

A root is a value \(x\) for which:

\[
f(x)=0
\]

The method repeatedly updates an estimate using:

\[
x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)}
\]

Here:

- \(x_n\) is the current estimate.
- \(f(x_n)\) is the function value at that estimate.
- \(f'(x_n)\) is the derivative.
- \(x_{n+1}\) is the next estimate.

### Example

Suppose we want to calculate the square root of 2 by finding the root of:

\[
f(x)=x^2-2
\]

Its derivative is:

\[
f'(x)=2x
\]

Using an initial estimate of \(x_0=1\), repeated iterations approach \(\sqrt{2}\).

### Suggested API

```python
import HyperMath as hm

solver = hm.newton_raphson(
    function=lambda x: x**2 - 2,
    derivative=lambda x: 2*x,
    initial_guess=1.0,
    tolerance=1e-10,
    max_iterations=100
)

result = solver.calculate()

print(result)
# Approximately 1.41421356237
```

### Parameters

| Parameter | Description |
|---|---|
| `function` | Function whose root is being calculated |
| `derivative` | Derivative of the function |
| `initial_guess` | Starting estimate |
| `tolerance` | Desired convergence tolerance |
| `max_iterations` | Maximum number of iterations |

### Return value

Returns an approximate root if the algorithm converges.

### Applications

- Solving nonlinear equations
- Numerical simulation
- Finding intersections and equilibrium points
- Scientific and engineering calculations

### Important considerations

The derivative must be nonzero at each iteration. The algorithm can fail to converge if the initial estimate is unsuitable or the function behaves poorly near the root.

The implementation should detect division by zero, non-finite values, and failure to converge within the iteration limit.

---

## 2. `discrete_fourier_transform` — Frequency Analysis

### Overview

The Discrete Fourier Transform (DFT) converts a finite sequence of samples into a representation of its frequency components.

For a sequence containing \(N\) samples:

\[
X_k=\sum_{n=0}^{N-1}x_n
e^{-i2\pi kn/N}
\]

Where:

- \(x_n\) is an input sample.
- \(X_k\) is a frequency-domain coefficient.
- \(N\) is the number of samples.
- \(i\) is the imaginary unit.

Each output coefficient describes the contribution of a particular discrete frequency bin.

### Example

```python
import HyperMath as hm

samples = [0, 1, 0, -1]

transform = hm.discrete_fourier_transform(
    samples=samples
)

result = transform.calculate()

print(result)
```

For this input, the DFT coefficients are mathematically equivalent to:

```python
[
    0j,
    -2j,
    0j,
    2j
]
```

Small floating-point errors may appear in a numerical implementation.

### Parameters

| Parameter | Description |
|---|---|
| `samples` | Finite sequence of real or complex values |

### Return value

Returns a sequence of complex frequency-domain coefficients.

### Applications

- Audio and signal analysis
- Frequency detection
- Periodic pattern analysis
- Procedural sound experiments
- Studying oscillations and sampled data

### Performance considerations

A direct DFT implementation requires \(O(N^2)\) operations.

For large inputs, a Fast Fourier Transform (FFT) algorithm is generally more efficient, typically requiring \(O(N\log N)\) operations for suitable input sizes.

A DFT implementation should document its output ordering and handling of empty inputs.

---

## 3. `bezier_curve` — Smooth Curves for Game Development

### Overview

A Bézier curve is a parametric curve controlled by a set of points.

It is widely used in animation, vector graphics, path generation, and game development.

For a quadratic Bézier curve:

\[
B(t)=(1-t)^2P_0+2(1-t)tP_1+t^2P_2
\]

Where:

- \(P_0\) is the starting point.
- \(P_1\) is the control point.
- \(P_2\) is the ending point.
- \(t\) ranges from 0 to 1.

At \(t=0\), the curve begins at \(P_0\). At \(t=1\), it reaches \(P_2\).

### Example

```python
import HyperMath as hm

curve = hm.bezier_curve(
    control_points=[
        (0, 0),
        (5, 10),
        (10, 0)
    ],
    t=0.5
)

point = curve.calculate()

print(point)
# (5.0, 5.0)
```

### Parameters

| Parameter | Description |
|---|---|
| `control_points` | Ordered list of control points |
| `t` | Position along the curve, normally from 0 to 1 |

### Return value

Returns a point on the curve, with the same dimensionality as the control points.

### Applications

- Smooth camera movement
- Character and object animation
- Curved projectile paths
- UI transitions
- Procedural paths and movement
- Interpolating between positions

### Important considerations

All control points must have the same dimensionality. For a conventional Bézier segment, `t` should lie between 0 and 1.

A general implementation can support linear, quadratic, cubic, and higher-degree curves using the de Casteljau algorithm.

---

## 4. `voronoi_nearest_point` — Nearest-Site Geometry

### Overview

A Voronoi diagram partitions space into regions. Each region contains the points that are closer to one designated site than to any other site.

The underlying nearest-site problem is straightforward: given a query point and a collection of sites, find the site with the smallest distance.

For two-dimensional Euclidean distance:

\[
d(P,Q)=\sqrt{(P_x-Q_x)^2+(P_y-Q_y)^2}
\]

### Example

```python
import HyperMath as hm

nearest = hm.voronoi_nearest_point(
    point=(4, 3),
    sites=[
        (0, 0),
        (5, 3),
        (10, 10)
    ]
)

result = nearest.calculate()

print(result)
# (5, 3)
```

### Parameters

| Parameter | Description |
|---|---|
| `point` | Query position |
| `sites` | Collection of candidate points |

### Return value

Returns the nearest site according to the selected distance metric.

### Applications

- Procedural terrain generation
- Nearest-city or nearest-building searches
- NPC territory assignment
- Map partitioning
- Spatial grouping
- Game-world region generation

### Important considerations

A simple implementation can calculate the distance to every site in \(O(N)\) time.

For very large collections, spatial indexes such as k-d trees may improve performance. If multiple sites are equally close, the API should document how ties are handled.

This function finds the nearest site; constructing a complete Voronoi diagram would be a separate, more advanced operation.

---

## 5. `adaptive_simpson_integration` — Numerical Integration

### Overview

Numerical integration estimates the area under a curve or evaluates a definite integral.

Adaptive Simpson's method approximates the integral using quadratic interpolation and recursively refines regions where the estimated error is too large.

For an interval \([a,b]\), Simpson's rule is:

\[
S(a,b)=\frac{b-a}{6}
\left[
f(a)+4f\left(\frac{a+b}{2}\right)+f(b)
\right]
\]

An adaptive implementation compares an estimate over the whole interval with estimates over two smaller intervals.

### Example

Calculate:

\[
\int_0^1 x^2\,dx=\frac13
\]

```python
import HyperMath as hm

integrator = hm.adaptive_simpson_integration(
    function=lambda x: x**2,
    a=0,
    b=1,
    tolerance=1e-10,
    max_depth=20
)

result = integrator.calculate()

print(result)
# Approximately 0.3333333333333333
```

### Parameters

| Parameter | Description |
|---|---|
| `function` | Function to integrate |
| `a` | Lower integration limit |
| `b` | Upper integration limit |
| `tolerance` | Desired error tolerance |
| `max_depth` | Maximum recursive subdivision depth |

### Return value

Returns an approximation of the definite integral.

### Applications

- Physics simulations
- Area and accumulated-value calculations
- Numerical analysis
- Probability distributions
- Scientific computing

### Important considerations

The tolerance is an error target, not a guarantee of the actual error for every function.

The implementation should handle reversed integration limits, recursion limits, non-finite function values, and functions with discontinuities. Such cases may require additional safeguards or a different integration method.

---

## 6. `lagrange_interpolation` — Estimating Values Between Data Points

### Overview

Lagrange interpolation constructs a polynomial that passes through a set of known data points.

Given \(n+1\) distinct points, the interpolating polynomial is:

\[
P(x)=\sum_{i=0}^{n}y_iL_i(x)
\]

where:

\[
L_i(x)=
\prod_{\substack{j=0\\j\ne i}}^{n}
\frac{x-x_j}{x_i-x_j}
\]

The polynomial passes through each supplied point, assuming all \(x_i\) values are distinct.

### Example

Suppose the known points are:

\[
(0,1),\quad(1,3),\quad(2,5)
\]

These points lie on the line \(y=2x+1\).

```python
import HyperMath as hm

interpolator = hm.lagrange_interpolation(
    points=[
        (0, 1),
        (1, 3),
        (2, 5)
    ],
    x=1.5
)

result = interpolator.calculate()

print(result)
# 4.0
```

### Parameters

| Parameter | Description |
|---|---|
| `points` | List of known `(x, y)` pairs |
| `x` | Position at which to estimate the value |

### Return value

Returns the interpolated value at the requested position.

### Applications

- Estimating values between samples
- Reconstructing simple curves from data
- Educational numerical mathematics
- Approximation of measured values
- Generating intermediate animation values

### Important considerations

All input \(x\)-coordinates must be distinct.

High-degree polynomial interpolation can behave poorly with many data points, particularly near the edges of an interval. For larger datasets, piecewise interpolation or spline methods may be more appropriate.

---

## 7. `quaternion_slerp` — Smooth 3D Rotation

### Overview

Quaternions are mathematical objects used to represent three-dimensional rotations.

Spherical linear interpolation (SLERP) interpolates between two unit quaternions along a shortest spherical path under the usual sign convention.

For unit quaternions \(q_0\) and \(q_1\), define:

\[
\cos\theta=q_0\cdot q_1
\]

Then, for the non-degenerate case:

\[
\operatorname{SLERP}(q_0,q_1,t)=
\frac{\sin((1-t)\theta)}{\sin\theta}q_0+
\frac{\sin(t\theta)}{\sin\theta}q_1
\]

Here \(t=0\) gives the starting orientation and \(t=1\) gives the ending orientation.

### Example

The following example assumes quaternions use the component order `(w, x, y, z)` and are normalized by the implementation.

```python
import HyperMath as hm
import math

q0 = (1, 0, 0, 0)

# Rotation of 90 degrees about the Z axis
q1 = (
    math.cos(math.pi / 4),
    0,
    0,
    math.sin(math.pi / 4)
)

interpolator = hm.quaternion_slerp(
    q0=q0,
    q1=q1,
    t=0.5
)

result = interpolator.calculate()

print(result)
# Approximately:
# (0.9238795, 0, 0, 0.3826834)
```

The result represents the intermediate orientation: approximately a 45-degree rotation about the Z axis.

### Parameters

| Parameter | Description |
|---|---|
| `q0` | Starting quaternion |
| `q1` | Ending quaternion |
| `t` | Interpolation parameter, normally from 0 to 1 |

### Return value

Returns an interpolated quaternion representing an orientation.

### Applications

- 3D character rotation
- Camera orientation
- Smooth aiming transitions
- Animation systems
- Interpolation between object orientations

### Important considerations

The implementation should account for non-unit inputs, floating-point rounding, and nearly identical quaternions.

Because \(q\) and \(-q\) represent the same rotation, a shortest-path implementation commonly flips one quaternion when their dot product is negative. Near-identical inputs generally need a normalized linear interpolation fallback.

---

## 8. `hilbert_curve_index` — Multidimensional Spatial Indexing

### Overview

A Hilbert curve is a space-filling curve that maps a multidimensional grid to a one-dimensional ordering while tending to keep nearby grid cells close in the resulting order.

This can be useful when multidimensional positions need to be represented by a single integer index.

For example, a two-dimensional integer coordinate:

\[
(x,y)
\]

can be mapped to a Hilbert index:

\[
H(x,y)
\]

The mapping depends on the grid's resolution and the chosen Hilbert-curve convention.

### Example

```python
import HyperMath as hm

indexer = hm.hilbert_curve_index(
    coordinates=(3, 5),
    bits=3
)

result = indexer.calculate()

print(result)
# An integer Hilbert index in the range 0 to 63
```

For a two-dimensional Hilbert curve with `bits=3`, each coordinate ranges from 0 to 7, producing \(2^{3\times2}=64\) possible grid positions.

The exact index depends on the implementation's coordinate orientation and bit-ordering convention.

### Parameters

| Parameter | Description |
|---|---|
| `coordinates` | Integer grid coordinates |
| `bits` | Number of bits per coordinate |

### Return value

Returns a non-negative integer representing the position in the Hilbert ordering.

### Applications

- Spatial indexing
- Organizing grid-based world data
- Locality-aware data storage
- Spatial database experiments
- Chunk and tile ordering
- Multidimensional data processing

### Important considerations

Coordinates must fit within the selected grid. For a two-dimensional curve with `bits=b`, each coordinate must lie between 0 and \(2^b-1\).

The algorithm must define how dimensions, orientation, and bit depth are handled. The reverse mapping from index to coordinates could be implemented as a separate function.

---

## 9. `markov_chain_step` — Probability Transitions

### Overview

A Markov chain models transitions between states using probabilities.

A state distribution represents the probability of occupying each state. A transition matrix specifies the probability of moving from one state to another.

Using a row-vector convention:

\[
\mathbf{p}_{\text{next}}=\mathbf{p}P
\]

where:

- \(\mathbf{p}\) is the current probability distribution.
- \(P\) is the transition matrix.
- \(\mathbf{p}_{\text{next}}\) is the next distribution.

Each row of \(P\) must sum to 1 for a conventional transition matrix.

### Example

Imagine a two-state model with states `A` and `B`.

The transition matrix is:

\[
P=
\begin{bmatrix}
0.8 & 0.2\\
0.3 & 0.7
\end{bmatrix}
\]

The current distribution is:

\[
\mathbf{p}=[1,0]
\]

After one step, the probability distribution becomes \([0.8,0.2]\).

```python
import HyperMath as hm

chain = hm.markov_chain_step(
    distribution=[1.0, 0.0],
    transition_matrix=[
        [0.8, 0.2],
        [0.3, 0.7]
    ]
)

result = chain.calculate()

print(result)
# [0.8, 0.2]
```

### Parameters

| Parameter | Description |
|---|---|
| `distribution` | Current state probabilities |
| `transition_matrix` | Matrix of transition probabilities |

### Return value

Returns the probability distribution after one transition.

### Applications

- Randomized simulations
- State-transition models
- Simple AI behavior models
- Probability experiments
- Modeling sequences of events
- Educational statistics

### Important considerations

The distribution must contain valid probabilities that sum to 1, and the transition matrix must have compatible dimensions.

A validation step should check that probabilities are finite and non-negative and that each transition row sums to 1 within a documented numerical tolerance.

This function performs one transition. Repeated transitions can be handled by calling it multiple times or by adding a separate multi-step operation.

---

## 10. `complex_iteration` — Iterative Complex Mathematics

### Overview

Complex iteration repeatedly applies a mathematical recurrence to a complex number.

A common example is:

\[
z_{n+1}=z_n^2+c
\]

where \(z_n\) and \(c\) are complex numbers.

This recurrence is important in the study of Julia sets and the Mandelbrot set. Iterating it can produce bounded or rapidly growing sequences depending on the initial value and parameter.

### Example

Start with:

\[
z_0=0,\qquad c=1
\]

Apply the recurrence three times:

\[
z_1=1
\]

\[
z_2=2
\]

\[
z_3=5
\]

The final value after three iterations is 5.

```python
import HyperMath as hm

iterator = hm.complex_iteration(
    initial_value=0 + 0j,
    parameter=1 + 0j,
    iterations=3
)

result = iterator.calculate()

print(result)
# (5+0j)
```

### Parameters

| Parameter | Description |
|---|---|
| `initial_value` | Starting complex number |
| `parameter` | Constant used in the recurrence |
| `iterations` | Number of iterations to perform |

### Return value

The proposed API returns the final complex value after the requested number of iterations.

An alternative design could return the entire sequence for visualization or further analysis.

### Applications

- Exploring complex dynamical systems
- Generating fractal data
- Mathematical visualization
- Studying iterative equations
- Educational experiments with complex numbers

### Important considerations

The iteration count should be a non-negative integer.

Complex values can grow extremely quickly, so implementations should consider overflow or non-finite values and optionally support an escape threshold for fractal-oriented calculations.

The recurrence should be explicitly documented. If users can provide arbitrary functions, the API should define how those functions are supplied and validated.

---

# Function Summary

| Function | Mathematical category | Main purpose |
|---|---|---|
| `newton_raphson` | Numerical analysis | Approximate equation roots |
| `discrete_fourier_transform` | Signal mathematics | Analyze frequency components |
| `bezier_curve` | Computational geometry | Calculate smooth curve positions |
| `voronoi_nearest_point` | Spatial geometry | Find the nearest site |
| `adaptive_simpson_integration` | Numerical analysis | Approximate definite integrals |
| `lagrange_interpolation` | Interpolation | Estimate values from known points |
| `quaternion_slerp` | 3D mathematics | Interpolate orientations |
| `hilbert_curve_index` | Spatial indexing | Map grid coordinates to an integer |
| `markov_chain_step` | Probability | Calculate a state transition |
| `complex_iteration` | Complex dynamics | Iterate complex-valued recurrences |

---

# Development Philosophy

HyperMath aims to provide reusable mathematical operations through a consistent and understandable interface.

The project prioritizes:

- **Reusability:** Avoid repeatedly writing the same mathematical algorithms.
- **Consistency:** Use a predictable API, including `.calculate()` where appropriate.
- **Reliability:** Validate inputs and handle mathematical edge cases.
- **Performance:** Choose suitable algorithms for the size and type of input.
- **Documentation:** Explain each function's purpose, arguments, output, and limitations.
- **Extensibility:** Continue adding useful mathematical capabilities over time.

A larger function collection is valuable when its functions are well tested, documented, and useful in real projects.

---

# Contributing and Feedback

Suggestions, bug reports, and ideas for additional mathematical functions are welcome.

When proposing a new function, consider:

1. What mathematical problem does it solve?
2. Does it duplicate an existing HyperMath function?
3. What inputs and outputs should it support?
4. What edge cases must be handled?
5. How can its correctness and performance be tested?

---

# License

See the repository's license information for the terms governing the use and distribution of HyperMath.

---

**HyperMath — Making reusable mathematical operations accessible to Python developers.**
