Skip to content

Commit

Permalink
Simplify helper function; fix docstring; update package version.
Browse files Browse the repository at this point in the history
  • Loading branch information
lapets committed Dec 31, 2024
1 parent d18f4d2 commit b4ad651
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 12 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "lagrange"
version = "3.0.0"
version = "3.0.1"
description = """\
Pure-Python implementation of Lagrange \
interpolation over finite fields.\
Expand Down
19 changes: 8 additions & 11 deletions src/lagrange/lagrange.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,22 @@
import functools
import itertools

def _inv(a: int, prime: int) -> int:
"""
Compute multiplicative inverse modulo a prime.
"""
return pow(a, prime - 2, prime)

def interpolate(
points: Union[dict, Sequence[int], Iterable[Sequence[int]]],
modulus: int,
degree: Optional[int] = None
) -> int:
"""
Determine the value at the origin of the domain (*e.g.*, where *x* = 0)
given a collection of points. The point information can be represented as
a collection of two-component coordinates, as a dictionary, or as a sequence
of values.
given a collection of points.
:param points: Collection of points to interpolate.
:param modulus: Modulus representing the finite field within which to interpolate.
:param degree: Degree of the target polynomial.
The point information can be represented as a collection of two-component
coordinates, as a dictionary, or as a sequence of values.
>>> interpolate([(1, 15), (2, 9), (3, 3)], 17)
4
>>> interpolate({1: 15, 2: 9, 3: 3}, 17)
Expand Down Expand Up @@ -158,6 +153,7 @@ def interpolate(
ValueError: expecting a nonnegative integer degree
"""
# pylint: disable=too-many-branches # Allow large number of branches for type checking.
# pylint: disable=unnecessary-lambda-assignment # Allow small local functions.
values = None # Initially, assume that the supplied point data is not valid.

if isinstance(points, dict):
Expand Down Expand Up @@ -224,8 +220,9 @@ def interpolate(
xs = list(values.keys())[:degree + 1]

# Field arithmetic helper functions.
mul = lambda a, b: (a % modulus) * b % modulus # pylint: disable=unnecessary-lambda-assignment
div = lambda a, b: mul(a, _inv(b, modulus)) # pylint: disable=unnecessary-lambda-assignment
inv = lambda a, p: pow(a, p - 2, p)
mul = lambda a, b: ((a % modulus) * b) % modulus
div = lambda a, b: mul(a, inv(b, modulus))

# Compute the value of each unique Lagrange basis polynomial at ``0``,
# then sum them all up to get the resulting value at ``0``.
Expand Down

0 comments on commit b4ad651

Please sign in to comment.