tweak: nim scratchpad

This commit is contained in:
NunoSempere 2023-05-20 21:45:01 -04:00
parent 88c079235e
commit dc27673887
5 changed files with 31 additions and 8 deletions

Binary file not shown.

View File

@ -7,20 +7,18 @@ proc pow2(x:float, y:int): float =
proc sine(x: float): float = proc sine(x: float): float =
let n = 100 let n = 100
var result = 0.0 var acc = 0.0
for i in 0..n: for i in 0..n:
let k = 2*n + 1 let k = 2*n + 1
let taylor = pow2(x, k)/ float(k) let taylor = pow2(x, k) / float(k)
result = result + taylor acc = acc + taylor
return result return acc
proc log(x: float): float = proc log(x: float): float =
var y = x - 1 var y = x - 1
var result = 0.0
let n = 1000 let n = 1000
for i in 1..n: for i in 1..n:
let taylor = pow2(-1, n+1) * pow2(y, n) / float(n) let taylor = pow2(-1.0, n+1) * pow2(y, n) / float(n)
let n = 1000
result = result + taylor result = result + taylor
return result return result
@ -31,4 +29,4 @@ proc normal(): float =
# see https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform#Basic_form # see https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform#Basic_form
echo log(1.0) echo sine(0.1)

2
wip/nim/sums/makefile Normal file
View File

@ -0,0 +1,2 @@
build: sums.nim
nim c sums.nim

BIN
wip/nim/sums/sums Executable file

Binary file not shown.

23
wip/nim/sums/sums.nim Normal file
View File

@ -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)