How to resolve the algorithm Sum of a series step by step in the Elm programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sum of a series step by step in the Elm programming language

Table of Contents

Problem Statement

Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence.
Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use:

This approximates the   zeta function   for   S=2,   whose exact value is the solution of the Basel problem.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sum of a series step by step in the Elm programming language

Source code in the elm programming language

module Main exposing (main)

import Html exposing (h1, div, p, text)
import Html.Attributes exposing (style)

aList : List Int 
aList = List.range 1 1000


-- version a with a list
k2xSum : Float
k2xSum = List.sum
  <| List.map (\x -> 1.0 / x / x ) 
    <| List.map (\n -> toFloat n) aList


-- version b with a list
fx : Int -> Float 
fx = 
    (\n -> toFloat n |> \m -> 1.0 / m / m)

f2kSum : Float
f2kSum = List.sum 
  <| List.map fx aList

-- version with recursion, without a list
untilMax : Int -> Int -> Float -> Float
untilMax k kmax accum =
  if k > kmax
    then accum
  else
    let 
        x = toFloat k
        dx = 1.0 / x / x 
    in  untilMax (k + 1)  kmax (accum + dx) 

recSum : Float
recSum = untilMax 1 1000 0.0 

main = div [style "margin" "5%", style "color" "blue"] [
   h1 [] [text "Sum of series Σ 1/k²"]
   , text (" Version a with a list: Sum = " ++ String.fromFloat k2xSum)
   , p [] [text (" Version b with a list: Sum = " ++ String.fromFloat f2kSum)]
   , p [] [text (" Recursion version c: Sum = " ++ String.fromFloat recSum)]
]


  

You may also check:How to resolve the algorithm Five weekends step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Knapsack problem/Unbounded step by step in the E programming language
You may also check:How to resolve the algorithm Loops/N plus one half step by step in the Swift programming language
You may also check:How to resolve the algorithm Arithmetic/Integer step by step in the NetRexx programming language
You may also check:How to resolve the algorithm Empty directory step by step in the Lua programming language