commit dc276738878e0ae293ded6850b7a0023b72ee019
parent 88c079235e3b2d95963bb6f7a48296bf43f1b431
Author: NunoSempere <nuno.sempere@protonmail.com>
Date: Sat, 20 May 2023 21:45:01 -0400
tweak: nim scratchpad
Diffstat:
5 files changed, 31 insertions(+), 8 deletions(-)
diff --git a/wip/nim/samples b/wip/nim/samples
Binary files differ.
diff --git a/wip/nim/samples.nim b/wip/nim/samples.nim
@@ -7,20 +7,18 @@ proc pow2(x:float, y:int): float =
proc sine(x: float): float =
let n = 100
- var result = 0.0
+ var acc = 0.0
for i in 0..n:
let k = 2*n + 1
- let taylor = pow2(x, k)/ float(k)
- result = result + taylor
- return result
+ let taylor = pow2(x, k) / float(k)
+ acc = acc + taylor
+ return acc
proc log(x: float): float =
var y = x - 1
- var result = 0.0
let n = 1000
for i in 1..n:
- let taylor = pow2(-1, n+1) * pow2(y, n) / float(n)
- let n = 1000
+ let taylor = pow2(-1.0, n+1) * pow2(y, n) / float(n)
result = result + taylor
return result
@@ -31,4 +29,4 @@ proc normal(): float =
# see https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform#Basic_form
-echo log(1.0)
+echo sine(0.1)
diff --git a/wip/nim/sums/makefile b/wip/nim/sums/makefile
@@ -0,0 +1,2 @@
+build: sums.nim
+ nim c sums.nim
diff --git a/wip/nim/sums/sums b/wip/nim/sums/sums
Binary files differ.
diff --git a/wip/nim/sums/sums.nim b/wip/nim/sums/sums.nim
@@ -0,0 +1,23 @@
+import std/math
+# randomize()
+
+proc factorial(n: int): int =
+ if n == 0 or n < 0:
+ return 1
+ else:
+ return n * factorial(n - 1)
+
+proc sine(x: float): float =
+ let n = 8
+ # ^ Taylor will converge really quickly
+ # notice that the factorial of 17 is
+ # already pretty gigantic
+ var acc = 0.0
+ for i in 0..n:
+ var k = 2*i + 1
+ var taylor = pow(-1, i.float) * pow(x, k.float) / factorial(k).float
+ acc = acc + taylor
+ return acc
+
+# echo factorial(17)
+echo sine(1.0)