2024-10-27 21:56:24 +01:00
|
|
|
#!/usr/bin/env julia
|
|
|
|
|
|
|
|
# Jacek Poziemski 272389
|
|
|
|
|
|
|
|
"""
|
2024-11-08 10:54:40 +01:00
|
|
|
f(x::Float64)::Float64
|
2024-10-27 21:56:24 +01:00
|
|
|
|
|
|
|
Calculate `sin(x) + cos(3x)`.
|
|
|
|
|
|
|
|
# Arguments
|
|
|
|
- `x::Float64`: function argument
|
|
|
|
"""
|
2024-11-08 12:29:30 +01:00
|
|
|
f(x::Float64)::Float64 = sin(x) + cos(Float64(3) * x)
|
2024-10-27 21:56:24 +01:00
|
|
|
|
|
|
|
"""
|
2024-11-08 10:54:40 +01:00
|
|
|
fderivative(x::Float64)::Float64
|
2024-10-27 21:56:24 +01:00
|
|
|
|
|
|
|
Calculate the derivative of `sin(x) + cos(3x)`, `cos(x) - 3sin(3x)`.
|
|
|
|
|
|
|
|
# Arguments
|
|
|
|
- `x::Float64`: function argument
|
|
|
|
"""
|
2024-11-08 12:29:30 +01:00
|
|
|
fderivative(x::Float64)::Float64 = cos(x) - Float64(3) * sin(Float64(3) * x)
|
2024-10-27 21:56:24 +01:00
|
|
|
|
|
|
|
"""
|
2024-11-08 10:54:40 +01:00
|
|
|
derivative(f::Function, x0::Float64, h::Float64)::Float64
|
2024-10-27 21:56:24 +01:00
|
|
|
|
|
|
|
Calculate an approximation of the derivative of `f` at `x0`,
|
|
|
|
using `h` in the following formula: `(f(x0 + h) - f(x0)) / h`.
|
|
|
|
|
|
|
|
# Arguments
|
|
|
|
- `f::Function`: function to calculate the derivative of
|
|
|
|
- `x0::Float64`: function argument
|
|
|
|
- `h::Float64`: value used in the approximation formula
|
|
|
|
"""
|
2024-11-08 12:29:30 +01:00
|
|
|
derivative(f::Function, x0::Float64, h::Float64)::Float64 = (f(x0 + h) - f(x0)) / h
|
2024-10-27 21:56:24 +01:00
|
|
|
|
2024-11-08 10:54:40 +01:00
|
|
|
x::Float64 = one(Float64)
|
2024-10-27 21:56:24 +01:00
|
|
|
|
2024-11-08 10:54:40 +01:00
|
|
|
for n::Int in 0:54
|
|
|
|
h::Float64 = 2.0^(-n)
|
|
|
|
d::Float64 = derivative(f, x, h)
|
|
|
|
e::Float64 = abs(fderivative(x) - d)
|
2024-10-27 21:56:24 +01:00
|
|
|
println("n: $n; h: $h; h + 1: $(h + 1); derivative: $d; error: $e")
|
|
|
|
end
|
|
|
|
|
|
|
|
println("exact value: $(fderivative(1.0))")
|