Skip to content

Commit

Permalink
Calculate point addition in general Weierstrass equation.
Browse files Browse the repository at this point in the history
test case
  • Loading branch information
shikil authored and abhinav-anand-addepar committed Feb 25, 2020
1 parent 6f7153b commit 51c044b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 6 deletions.
28 changes: 22 additions & 6 deletions sympy/ntheory/ec.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,15 @@ class EllipticCurvePoint():
>>> e3 = EllipticCurve(-1, 9)
>>> e3(1, -3) * 3
(664/169, 17811/2197)
>>> e2 = EC(-2, 0, 0, 1, 1)
>>> p = e2(-1,1)
>>> q = e2(0, -1)
>>> p+q
(4, 8)
>>> p-q
(1, 0)
>>> 3*p-5*q
(328/361, -2800/6859)
"""

@staticmethod
Expand All @@ -277,16 +285,21 @@ def __add__(self, p):
return self
x1, y1 = self.x, self.y
x2, y2 = p.x, p.y
a1 = self._curve._a1
a2 = self._curve._a2
a3 = self._curve._a3
a4 = self._curve._a4
a6 = self._curve._a6
if x1 != x2:
slope = (y1 - y2) / (x1 - x2)
yint = (y1 * x2 - y2 * x1) / (x2 - x1)
else:
if (y1 + y2) == 0:
return self.point_at_infinity(self._curve)
a4 = self._curve._a4
slope = (3 * x1**2 + 2*a2 + a4) / (2 * y1)
x3 = slope**2 - a2 - x1 - x2
y3 = -y1 - slope * (x3 - x1)
slope = (3 * x1**2 + 2*a2*x1 + a4 - a1*y1) / (a1 * x1 + a3 + 2 * y1)
yint = (-x1**3 + a4*x1 + 2*a6 - a3*y1) / (a1*x1 + a3 + 2*y1)
x3 = slope**2 + a1*slope - a2 - x1 - x2
y3 = -(slope + a1) * x3 - yint - a3
return EllipticCurvePoint(x3, y3, 1, self._curve)

def __lt__(self, other):
Expand All @@ -311,7 +324,7 @@ def __rmul__(self, n):
return self * n

def __neg__(self):
return EllipticCurvePoint(self.x, -self.y, self.z, self._curve)
return EllipticCurvePoint(self.x, -self.y - self._curve._a1*self.x - self._curve._a3, self.z, self._curve)

def __repr__(self):
if self.z == 0:
Expand All @@ -323,6 +336,9 @@ def __repr__(self):
pass
return '({}, {})'.format(self.x, self.y)

def __sub__(self, other):
return self + -other

def order(self):
"""
Return point order n where nP = 0.
Expand Down
18 changes: 18 additions & 0 deletions sympy/ntheory/tests/test_ec.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from sympy.ntheory.ec import EllipticCurve
def test_elliptic_curve():
# Point addition and multiplication
e3 = EllipticCurve(-1, 9)
p = e3(0, 3)
q = e3(-1, 3)
r = p + q
assert r.x == 1 and r.y == -3
r = 2*p + q
assert r.x == 35 and r.y == 207
r = -p + q
assert r.x == 37 and r.y == 225
# Verify result in http://www.lmfdb.org/EllipticCurve/Q
# Discriminant
assert EllipticCurve(-1, 9).discriminant == -34928
assert EllipticCurve(-2731, -55146, 1, 0, 1).discriminant == 25088
# Torsion points
assert len(EllipticCurve(0, 1).torsion_points()) == 6

0 comments on commit 51c044b

Please sign in to comment.