Created
March 23, 2024 09:02
-
-
Save mb6ockatf/f71b904a41a4c5a49411b1e5e64a59cc to your computer and use it in GitHub Desktop.
use newton method to count logarithms; monte-carlo method to compute pi digits; compute square roots with given precision
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/julia | |
using Test | |
const EPS = 1e-11 | |
function log_core(base::Float64, n::Float64) | |
x = 1 | |
step = 1 | |
while step > EPS | |
while base ^ x < n | |
x += step | |
end | |
x -= step | |
step = step / 10 | |
end | |
return x + step | |
end | |
function log(base::Float64, n::Float64) | |
if base < 0 || n < 0 | |
return "error" | |
end | |
if base < 1 && n < 1 | |
return log_core(1/base, 1/n) | |
elseif base > 1 && n > 1 | |
return log_core(base, n) | |
elseif base < 1 && n > 1 | |
return - log_core(1/base, n) | |
elseif base > 1 && n < 1 | |
return log_core(base, 1/n) | |
end | |
end | |
@testset "log" begin | |
@test 6 < div(log(Float64(2), Float64(128)), 1) < 8 | |
end; | |
println(log(Float64(5), Float64(8))) | |
println(log(Float64(3), Float64(27))) | |
println(log(Float64(3), Float64(81))) | |
println(log(Float64(5), Float64(125))) | |
println(log(Float64(0.5), Float64(1/128))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/julia | |
function calc_pi() | |
Ox, Oy = 100000, 100000 | |
inside = 0 | |
attempts = 10000000 | |
for i = 1:attempts | |
x, y = rand(0:Ox), rand(0:Oy) | |
if (x ^ 2 + y ^ 2) ^ 0.5 < Ox | |
inside = inside + 1 | |
end | |
end | |
return inside / attempts * 4 | |
end | |
print(calc_pi()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/julia | |
const eps = 1e-15; | |
function sqrt(n::Int64) | |
x = 1; | |
while abs(x * x - n) > eps | |
x = (x + n / x) / 2; | |
end | |
return x; | |
end | |
println(sqrt(7)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment