Elliptic curve arithmetic
1
module EC {
2
3
var A = 0
4
var B = 7
5
6
class Horizon {
7
method to_s {
8
"EC Point at horizon"
9
}
10
11
method *(_) {
12
self
13
}
14
15
method -(_) {
16
self
17
}
18
}
19
20
class Point(Number x, Number y) {
21
method to_s {
22
"EC Point at x=#{x}, y=#{y}"
23
}
24
25
method neg {
26
Point(x, -y)
27
}
28
29
method -(Point p) {
30
self + -p
31
}
32
33
method +(Point p) {
34
35
if (x == p.x) {
36
return (y == p.y ? self*2 : Horizon())
37
}
38
else {
39
var slope = (p.y - y)/(p.x - x)
40
var x2 = (slope**2 - x - p.x)
41
var y2 = (slope * (x - x2) - y)
42
Point(x2, y2)
43
}
44
}
45
46
method +(Horizon _) {
47
self
48
}
49
50
method *((0)) {
51
Horizon()
52
}
53
54
method *((1)) {
55
self
56
}
57
58
method *((2)) {
59
var l = (3 * x**2 + A)/(2 * y)
60
var x2 = (l**2 - 2*x)
61
var y2 = (l * (x - x2) - y)
62
Point(x2, y2)
63
}
64
65
method *(Number n) {
66
2*(self * (n>>1)) + self*(n % 2)
67
}
68
}
69
70
class Horizon {
71
method +(Point p) {
72
p
73
}
74
}
75
76
class Number {
77
method +(Point p) {
78
p + self
79
}
80
method *(Point p) {
81
p * self
82
}
83
method *(Horizon h) {
84
h
85
}
86
method -(Point p) {
87
-p + self
88
}
89
}
90
}
91
92
say var p = with(1) {|v| EC::Point(v, sqrt(abs(1 - v**3 - EC::A*v - EC::B))) }
93
say var q = with(2) {|v| EC::Point(v, sqrt(abs(1 - v**3 - EC::A*v - EC::B))) }
94
say var s = (p + q)
95
96
say ("checking alignment: ", abs((p.x - q.x)*(-s.y - q.y) - (p.y - q.y)*(s.x - q.x)) < 1e-20)
Copied!

Output:

1
EC Point at x=1, y=2.64575131106459059050161575363926042571025918308
2
EC Point at x=2, y=3.74165738677394138558374873231654930175601980778
3
EC Point at x=-1.79898987322333068322364213893577309997540625528, y=0.421678696849803028974882458314430376814790014487
4
checking alignment: true
Copied!
Last modified 1yr ago
Copy link
Contents
Output: