How to resolve the algorithm Polynomial regression step by step in the Wren programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Polynomial regression step by step in the Wren programming language

Table of Contents

Problem Statement

Find an approximating polynomial of known degree for a given data. Example: For input data: The approximating polynomial is: Here, the polynomial's coefficients are (3, 2, 1). This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Polynomial regression step by step in the Wren programming language

Source code in the wren programming language

import "/math" for Nums
import "/seq" for Lst
import "/fmt" for Fmt

var polynomialRegression = Fn.new { |x, y|
    var xm   = Nums.mean(x)
    var ym   = Nums.mean(y)
    var x2m  = Nums.mean(x.map { |e| e * e })
    var x3m  = Nums.mean(x.map { |e| e * e * e })
    var x4m  = Nums.mean(x.map { |e| e * e * e * e })
    var z    = Lst.zip(x, y)
    var xym  = Nums.mean(z.map { |p| p[0] * p[1] })
    var x2ym = Nums.mean(z.map { |p| p[0] * p[0] * p[1] })

    var sxx   = x2m - xm * xm
    var sxy   = xym - xm * ym
    var sxx2  = x3m - xm * x2m
    var sx2x2 = x4m - x2m * x2m
    var sx2y  = x2ym - x2m * ym

    var b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
    var c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
    var a = ym - b * xm - c * x2m

    var abc = Fn.new { |xx| a + b * xx + c * xx * xx }

    System.print("y = %(a) + %(b)x + %(c)x^2\n")
    System.print(" Input  Approximation")
    System.print(" x   y     y1")
    for (p in z) Fmt.print("$2d $3d  $5.1f", p[0], p[1], abc.call(p[0]))
}

var x = List.filled(11, 0)
for (i in 1..10) x[i] = i
var y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]
polynomialRegression.call(x, y)

  

You may also check:How to resolve the algorithm Perfect shuffle step by step in the Sidef programming language
You may also check:How to resolve the algorithm Input loop step by step in the Run BASIC programming language
You may also check:How to resolve the algorithm Mandelbrot set step by step in the Haxe programming language
You may also check:How to resolve the algorithm Pythagorean quadruples step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Window creation/X11 step by step in the PicoLisp programming language