How to resolve the algorithm Roots of a function step by step in the Nim programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Roots of a function step by step in the Nim programming language

Table of Contents

Problem Statement

Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.

For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Roots of a function step by step in the Nim programming language

Source code in the nim programming language

import math
import strformat

func f(x: float): float = x ^ 3 - 3 * x ^ 2 + 2 * x

var 
  step = 0.01
  start = -1.0
  stop = 3.0
  sign = f(start) > 0
  x = start

while x <= stop:
  var value = f(x)
  
  if value == 0:
    echo fmt"Root found at {x:.5f}"
  elif (value > 0) != sign:
    echo fmt"Root found near {x:.5f}"
  
  sign = value > 0
  x += step


  

You may also check:How to resolve the algorithm Twin primes step by step in the C programming language
You may also check:How to resolve the algorithm Read a file line by line step by step in the REXX programming language
You may also check:How to resolve the algorithm Averages/Root mean square step by step in the Ada programming language
You may also check:How to resolve the algorithm Averages/Mean time of day step by step in the Delphi programming language
You may also check:How to resolve the algorithm Pascal's triangle/Puzzle step by step in the Craft Basic programming language