Jump to content

Elliptic curve arithmetic: Difference between revisions

Added EchoLisp
(Python solution)
(Added EchoLisp)
Line 206:
a + b + d = Zero
a * 12345 = (10.759, 35.387)</pre>
 
=={{header|EchoLisp}}==
===Arithmetic===
<lang scheme>
(require 'struct)
(decimals 4)
(string-delimiter "")
(struct pt (x y))
 
(define-syntax-id _.x (struct-get _ #:pt.x))
(define-syntax-id _.y (struct-get _ #:pt.y))
 
(define (E-zero) (pt Infinity Infinity))
(define (E-zero? p) (= (abs p.x) Infinity))
(define (E-neg p) (pt p.x (- p.y)))
 
;; magic formulae from "C"
;; p + p
(define (E-dbl p)
(if (E-zero? p) p
(let* (
[L (// (* 3 p.x p.x) (* 2 p.y))]
[rx (- (* L L) (* 2 p.x))]
[ry (- (* L (- p.x rx)) p.y)]
)
(pt rx ry))))
;; p + q
(define (E-add p q)
(cond
[ (and (= p.x p.x) (= p.y q.y)) (E-dbl p)]
[ (E-zero? p) q ]
[ (E-zero? q) p ]
[ else
(let* (
[L (// (- q.y p.y) (- q.x p.x))]
[rx (- (* L L) p.x q.x)] ;; match
[ry (- (* L (- p.x rx)) p.y)]
)
(pt rx ry))]))
;; (E-add* a b c ...)
(define (E-add* . pts) (foldl E-add (E-zero) pts))
 
;; p * n
(define (E-mul p n (r (E-zero)) (i 1))
(while (<= i n)
(when (!zero? (bitwise-and i n)) (set! r (E-add r p)))
(set! p (E-dbl p))
(set! i (* i 2)))
r)
;; make points from x or y
(define (Ey.pt y (c 7))
(pt (expt (- (* y y) c) 1/3 ) y))
(define (Ex.pt x (c 7))
(pt x (sqrt (+ ( * x x x ) c))))
 
;; Check floating point precision
;; P * n is not always P+P+P+P....P
 
(define (E-ckmul a n )
(define e a)
(for ((i (in-range 1 n))) (set! e (E-add a e)))
(printf "%d additions a+(a+(a+...))) → %a" n e)
(printf "multiplication a x %d → %a" n (E-mul a n)))
</lang>
{{out}}
<pre>
(define P (Ey.pt 1))
(define Q (Ey.pt 2))
(define R (E-add P Q))
→ #<pt> (10.3754 -33.5245)
(E-zero? (E-add* P Q (E-neg R)))
→ #t
(E-mul P 12345)
→ #<pt> (10.7586 35.3874)
 
;; check floating point precision
(E-ckmul P 10) ;; OK
10 additions a+(a+(a+...))) → #<pt> (0.3797 -2.6561)
multiplication a x 10 → #<pt> (0.3797 -2.6561)
 
(E-ckmul P 12345) ;; KO
12345 additions a+(a+(a+...))) → #<pt> (-1.3065 2.4333)
multiplication a x 12345 → #<pt> (10.7586 35.3874)
</pre>
===Plotting===
;; Result at http://www.echolalie.org/echolisp/help.html#plot-xy
<lang scheme>
(define (E-plot (r 3))
(define (Ellie x y) (- (* y y) (* x x x) 7))
(define P (Ey.pt 0))
(define Q (Ex.pt 0))
(define R (E-add P Q))
(plot-clear)
(plot-xy Ellie -10 -10) ;; curve
(plot-axis 0 0 "red")
(plot-circle P.x P.y r) ;; points
(plot-circle Q.x Q.y r)
(plot-circle R.x R.y r)
(plot-circle R.x (- R.y) r)
(plot-segment P.x P.y R.x (- R.y))
(plot-segment R.x R.y R.x (- R.y))
)
</lang>
 
=={{header|Go}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.