Skip to content
This repository was archived by the owner on Jan 13, 2024. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions .github/workflows/Documenter.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: Documenter
on:
push:
branches:
- main
tags: '*'
pull_request:
jobs:
build:
runs-on: ubuntu-latest # [ubuntu-latest, windows-latest, macOS-latest]
steps:
- uses: actions/checkout@v2
- uses: julia-actions/setup-julia@latest
with:
version: '1.8.5'
- name: Check Git installation
run: git --version
- name: Install dependencies
run: julia --project=docs/ -e 'using Pkg; Pkg.develop(PackageSpec(path=pwd())); Pkg.instantiate()'
- name: Build and deploy
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # For authentication with GitHub Actions token
DOCUMENTER_KEY: ${{ secrets.DOCUMENTER_KEY }} # For authentication with SSH deploy key
run: julia --project=docs/ docs/make.jl
21 changes: 21 additions & 0 deletions .github/workflows/Runtests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: Runtests
on:
push:
pull_request:
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
julia-version: ['1.8.5']
julia-arch: [x64]
os: [ubuntu-latest] # [ubuntu-latest, windows-latest, macOS-latest]
steps:
- uses: actions/checkout@v2
- uses: julia-actions/setup-julia@v1
with:
version: ${{ matrix.julia-version }}
- uses: julia-actions/julia-buildpkg@latest
- name: Run tests
uses: julia-actions/julia-runtest@latest

11 changes: 11 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"spellright.language": [
"en",
"sl"
],
"spellright.documentTypes": [
"markdown",
"latex",
"plaintext"
]
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 jakob

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 2 additions & 0 deletions Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@ authors = ["lovc21 <jakob.dekleva@gmail.com>"]
version = "0.1.0"

[deps]
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Interpolation using Barycentric Formula

[![Documenter](https://github.com/lovc21/Interpolation_with_the_barycentric_formula.jl/actions/workflows/Documenter.yml/badge.svg)](https://github.com/lovc21/Interpolation_with_the_barycentric_formula.jl/actions/workflows/Documenter.yml)
[![Runtests](https://github.com/lovc21/Interpolation_with_the_barycentric_formula.jl/actions/workflows/Runtests.yml/badge.svg)](https://github.com/lovc21/Interpolation_with_the_barycentric_formula.jlin/actions/workflows/Runtests.yml)

In this repository, you can finde the code for Homework 3 of the Numerical Methods course.The code is written in Julia, and the main implementation can be found in the file `src/Interpolation_with_the_barycentric_formula.jl`. The code is tested using the file `test/runtests.jl`, and it is documented using the file docs/make.jl, you can test the code for the specific by running the `Scripts/script.jl` file.

To run the code, it is necessary to have Julia installed on your computer. Once downloaded, you can run the code for the following equations: e^(-x^2) on \([-1,1]\) , sin(x)/x on \([0,10]\) and |x^2-2x| on \([1,3]\).To run the code, you can simply start the script `Scripts/script.jl`.The script will compute the interpolation for the three equations and will return the reuslts to the precision of 1e-6.

The code and the Mathematical backround is documented using Documenter.jl. To see the documentation, you can run the docs/make.jl file. The documentation is also available online at [documentation](https://lovc21.github.io/Interpolation_with_the_barycentric_formula.jl/dev/).

---
Here are the results of the interpolation for the three equations for the nodes 1 ,3 the number so that the error is less than 1e-6:

1. e^(-x^2)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would comment about the results you presented. What are sufficient number of nodes for the exemples and why they are different?

<p align="center">
<img width="460" height="300" src="./images/ezgif-4-cfcfa1457c.gif">
</p>

2. sin(x)/x
<p align="center">
<img width="460" height="300" src="./images/ezgif-4-e9a28c1c2b.gif">
</p>

3. |x^2-2x|
<p align="center">
<img width="460" height="300" src="./images/ezgif-4-53e4254853.gif">
</p>
19 changes: 19 additions & 0 deletions Scripts/Ploting.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@

using Plots

x1 = -1:0.01:1
x2 = 0.01:0.1:10
x3 = 1:0.01:3

f1(x) = exp(-x^2)
f2(x) = sin(x) / x
#f2(x) = x == 0 ? 1 : sin(x)/x
f3(x) = abs(x^2 - 2x)

# Plot the functions
plot(x1, f1.(x1), label="e^{-x^2}", legend=:topright)

plot(x2, f2.(x2), label="sin(x)/x")

plot(x3, f3.(x3), label="|x^2-2x|")

39 changes: 39 additions & 0 deletions Scripts/script.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using Interpolation_with_the_barycentric_formula

precision = 1e-6
n = 10

f1(x) = exp.(-x.^2)
#f2(x) = sin.(x) ./ x to ne dela
f2(x) = x == 0 ? 1 : sin(x)/x # to dela
f3(x) = abs.(x.^2 - 2 .* x)

functions = [f1, f2, f3]
intervals = [(-1, 1), (0, 10), (1, 3)]
names = ["exp(-x^2)", "sin(x)/x", "|x^2 - 2x|"]


# Calculate and print the optimal degree for each function
for (i, f) in enumerate(functions)
degree = get_optimal_degree(f, intervals[i][1], intervals[i][2], n, precision)
println("Optimal degree for $(names[i]) on [$(intervals[i][1]), $(intervals[i][2])]: $degree")
end

# Compute the maximum error for each function at the optimal degrees and print the results
degrees = [10, 13, 1567]
for (i, f) in enumerate(functions)
error = compute_max_error(f, intervals[i][1], intervals[i][2], degrees[i])
println("Maximum error for $(names[i]) on [$(intervals[i][1]), $(intervals[i][2])]: $error")
end

# Display the plots for each function for increasing n values up to their max degrees
for (i, f) in enumerate(functions)
for n in [1, 3, degrees[i]]
p = plot_interpolation(f, intervals[i][1], intervals[i][2], n, names[i])
display(p)
sleep(2)
end
end



8 changes: 5 additions & 3 deletions docs/make.jl
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ makedocs(
# Documenter can also automatically deploy documentation to gh-pages.
# See "Hosting Documentation" and deploydocs() in the Documenter manual
# for more information.
#=deploydocs(
repo = "<repository url>"
)=#
deploydocs(
repo = "github.com/lovc21/Interpolation_with_the_barycentric_formula.jl.git",
push_preview = true,
devbranch = "main",
)
Binary file added docs/src/images/ezgif-4-53e4254853.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/src/images/ezgif-4-cfcfa1457c.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/src/images/ezgif-4-e9a28c1c2b.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
161 changes: 159 additions & 2 deletions docs/src/index.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,160 @@
# Interpolation_with_the_barycentric_formula.jl
# Interpolation with the barycentric formula

Documentation for Interpolation_with_the_barycentric_formula.jl
This is the documentation for the repository of homework 3 Interpolation with the barycentric formula of the course Numerical Methods. This documentation is devided in two parts: the first one is the documentation of the mathematical backround of the task and the second part is the documentation of the code we used to solve the task.

## Mathematical backround

### Introduction
The point of the given task is to numerically interpolate the following function: e^(-x^2) on \([-1,1]\) , sin(x)/x on \([0,10]\) and |x^2-2x| on \([1,3]\). The interpolation is done with the barycentric formula and Chebyshev points.

### Chebyshev points
Chebyshev points are the roots of the Chebyshev polynomials. The Chebyshev polynomials are defined as a sequence of orthogonal polynomials defined on the interval [−1,1].

Chebyshev points of the first kind in the interval [−1,1] are given by the formula:

<table align="center">
<tr>
<td>
<img src=https://latex.codecogs.com/svg.latex?x_k%20%3D%20%5Ccos%5Cleft%28%5Cfrac%7B%282k&plus;1%29%5Cpi%7D%7B2%28n&plus;1%29%7D%5Cright%29>
</td>
</tr>
</table>

And for the Chebyshev points on the interval [a, b]:

<table align="center">
<tr>
<td>
<img src=https://latex.codecogs.com/svg.latex?x_k%20%3D%20%5Cfrac%7Ba&plus;b%7D%7B2%7D%20&plus;%20%5Cfrac%7Bb-a%7D%7B2%7D%20%5Ccos%5Cleft%28%5Cfrac%7B%282k&plus;1%29%5Cpi%7D%7B2%28n&plus;1%29%7D%5Cright%29>
</td>
</tr>
</table>

### Barycentric formula
The barycentric formula is a method for numerical interpolation. It is based on the Lagrange interpolation formula. The Lagrange interpolation formula is the following:

<table align="center">
<tr>
<td>
<img src=https://latex.codecogs.com/svg.latex?p(x)%20=%20\sum_{j=0}^{n}%20f(x_j)%20\ell_j(x)>
</td>
</tr>
</table>

But this formula is numerically unstable, so we use the barycentric formula instead. The barycentric formula is the following:

<table align="center">
<tr>
<td>
<img src=https://latex.codecogs.com/svg.latex?p(x)%20=%20\frac{\sum_{j=0}^{n}%20\lambda_j%20f(x_j)%20/%20(x%20-%20x_j)}{\sum_{j=0}^{n}%20\lambda_j%20/%20(x%20-%20x_j)}>
</td>
</tr>
</table>

This formula offers a numerically stable way to interpolate a function and it is also faster than the Lagrange interpolation formula.

### The results of the interpolation
The following pictures show the results of the interpolation of the given functions with the barycentric formula and Chebyshev points.

1. e^(-x^2)
<p align="center">
<img width="460" height="300" src="./images/ezgif-4-cfcfa1457c.gif">
</p>

2. sin(x)/x
<p align="center">
<img width="460" height="300" src="./images/ezgif-4-e9a28c1c2b.gif">
</p>

3. |x^2-2x|
<p align="center">
<img width="460" height="300" src="./images/ezgif-4-53e4254853.gif">
</p>

## Code documentation
First we calculate the Chebyshev nodes using the second formula for the Chebyshev points. We use the following function to calculate the Chebyshev nodes:

```julia
function chebyshev_nodes(n, a, b)

# Check the nodes calculation
nodes = [cos(π * (i / n)) for i in 0:n]

# Check the mapping to the interval
mapped_nodes = [(a + b) / 2 + (b - a) / 2 * x for x in nodes]

return mapped_nodes
end
```
Next we calculate the weights for the barycentric formula. We use the following function to calculate the weights:

```julia
function chebyshev_weights(n)
weights = [Float64((-1)^i) for i in 0:n]
weights[1] *= 0.5
weights[end] *= 0.5
return weights
end
```
After that we can caculate the barycentric interpolation using the barycentric formula. We use the following function to calculate the barycentric interpolation:
```julia
function barycentric_interpolation(nodes,values, weights, x)
if x in nodes
return values[nodes .== x][1]
else
# Calculate the numerator
numerator = sum(values[i] * weights[i] ./ (x .- nodes[i]) for i in 1:length(nodes))
# Calculate the denominator
denominator = sum(weights[i] ./ (x .- nodes[i]) for i in 1:length(nodes))
end

return numerator / denominator
end
```

After we have the barycentric interpolation we can run the code so that we are in the exaptible level of precision. We use the following function to run the code:
```julia
function get_optimal_degree(func, a, b,n,precision)
while true
nodes = chebyshev_nodes(n, a, b)
values = [func(node) for node in nodes]
weights = chebyshev_weights(n)

test_points = range(a, stop=b, length=1000)
max_error = 0.0

for x in test_points
interpolated_value = barycentric_interpolation(nodes, values, weights, x)
error = abs(func(x) - interpolated_value)
max_error = max(max_error, error)
end

if max_error < precision
return n
end

n += 1

end
end
```

Finally we can plot the results of the interpolation. We use the following function to plot the results:
```julia
function plot_interpolation(f, a, b, n, name)
nodes = chebyshev_nodes(n, a, b)
values = [f(node) for node in nodes]
weights = chebyshev_weights(n)

x_vals = range(a, stop=b, length=1000)
y_true = [f(x) for x in x_vals]
y_interp = [barycentric_interpolation(nodes, values, weights, x) for x in x_vals]

p = plot(x_vals, y_true, label="Original $name", lw=2)
plot!(p, x_vals, y_interp, label="Interpolated $name n=$n", linestyle=:dash, lw=2)
title!("Interpolation of $name with degree $n")
xlabel!("x")
ylabel!("f(x)")
return p
end
```
Binary file added images/ezgif-4-53e4254853.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/ezgif-4-cfcfa1457c.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/ezgif-4-e9a28c1c2b.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading