non linearity

This commit is contained in:
2026-05-18 15:23:22 +02:00
parent 84fda8757c
commit c0e275c734
3 changed files with 31 additions and 1 deletions
+2 -1
View File
@@ -2,7 +2,7 @@ from __future__ import annotations
import sys
from .walsh import walsh_transform
from .walsh import walsh_transform, nonlinearity
def main() -> None:
@@ -12,6 +12,7 @@ def main() -> None:
expr = input("Enter formula: ").strip()
print(walsh_transform(expr))
print("non-linearity:", nonlinearity(expr))
if __name__ == "__main__":
+16
View File
@@ -66,3 +66,19 @@ def walsh_transform(
coeffs.append(total)
return coeffs
def nonlinearity(
expr: str | Poly,
variables: Sequence[str] | None = None,
) -> int:
"""
NL(f) = 2^(n-1) - max_u |W_f(u)| / 2
"""
poly = parse_boolean_expression(expr) if isinstance(expr, str) else expr
vars_ = list(variables) if variables is not None else infer_variables(poly)
n = len(vars_)
spectrum = walsh_transform(poly, vars_)
return (1 << (n - 1)) - max(abs(w) for w in spectrum) // 2
+13
View File
@@ -0,0 +1,13 @@
from walsh.walsh import nonlinearity
def test_nonlinearity_linear_function():
assert nonlinearity("x1 XOR x2") == 0
def test_nonlinearity_or():
assert nonlinearity("x1 OR x2") == 1
def test_nonlinearity_majority():
assert nonlinearity("x1*x2 XOR x1*x3 XOR x2*x3") == 2