How to resolve the algorithm Numerical integration step by step in the Elixir programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Numerical integration step by step in the Elixir programming language

Table of Contents

Problem Statement

Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code:

Demonstrate your function by showing the results for:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Numerical integration step by step in the Elixir programming language

Source code in the elixir programming language

defmodule Numerical do
  @funs  ~w(leftrect midrect rightrect trapezium simpson)a
 
  def  leftrect(f, left,_right), do: f.(left)
  def   midrect(f, left, right), do: f.((left+right)/2)
  def rightrect(f,_left, right), do: f.(right)
  def trapezium(f, left, right), do: (f.(left)+f.(right))/2
  def   simpson(f, left, right), do: (f.(left) + 4*f.((left+right)/2.0) + f.(right)) / 6.0
 
  def integrate(f, a, b, steps) when is_integer(steps) do
    delta = (b - a) / steps
    Enum.each(@funs, fn fun ->
      total = Enum.reduce(0..steps-1, 0, fn i, acc ->
        left = a + delta * i
        acc + apply(Numerical, fun, [f, left, left+delta])
      end)
      :io.format "~10s : ~.6f~n", [fun, total * delta]
    end)
  end
end
 
f1 = fn x -> x * x * x end
IO.puts "f(x) = x^3, where x is [0,1], with 100 approximations."
Numerical.integrate(f1, 0, 1, 100)
 
f2 = fn x -> 1 / x end
IO.puts "\nf(x) = 1/x, where x is [1,100], with 1,000 approximations. "
Numerical.integrate(f2, 1, 100, 1000)
 
f3 = fn x -> x end
IO.puts "\nf(x) = x, where x is [0,5000], with 5,000,000 approximations."
Numerical.integrate(f3, 0, 5000, 5_000_000)
 
f4 = fn x -> x end
IO.puts "\nf(x) = x, where x is [0,6000], with 6,000,000 approximations."
Numerical.integrate(f4, 0, 6000, 6_000_000)


  

You may also check:How to resolve the algorithm Sequence of non-squares step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Pinstripe/Display step by step in the Wren programming language
You may also check:How to resolve the algorithm Check Machin-like formulas step by step in the Julia programming language
You may also check:How to resolve the algorithm Parsing/Shunting-yard algorithm step by step in the C programming language
You may also check:How to resolve the algorithm Sort stability step by step in the Groovy programming language