TheAlgorithms-C-Plus-Plus/numerical_methods/durand_kerner_roots.cpp
Krishna Vedala aaa08b0150
Major rework to improve code quality and add automation checks (#805)
* delete secant method - it is identical to regula falsi

* document + improvize root finding algorithms

* attempt to document gaussian elimination

* added file brief

* commented doxygen-mainpage, added files-list link

* corrected files list link path

* files-list link correction - this time works :)

* document successive approximations

* cleaner equation

* updating DIRECTORY.md

* documented kmp string search

* document brute force string search

* document rabin-karp string search

* fixed mainpage readme

* doxygen v1.8.18 will suppress out the #minipage in the markdown

* cpplint correction for header guard style

* github action to auto format source code per cpplint standard

* updated setting to add 1 space before `private` and `public` keywords

* auto rename files and auto format code

* added missing "run" for step

* corrected asignmemt operation

* fixed trim and assign syntax

* added git move for renaming bad filenames

* added missing pipe for trim

* added missing space

* use old and new fnames

* store old fname using echo

* move files only if there is a change in filename

* put old filenames in quotes

* use double quote for old filename

* escape double quotes

* remove old_fname

* try escape characters and echo"

* add file-type to find

* cleanup echo

* ensure all trim variables are also in quotes

* try escape -quote again

* remove second escpe quote

* use single quote for first check

* use carets instead of quotes

* put variables in brackets

* remove -e from echo

* add debug echos

* try print0 flag

* find command with while instead of for-loop

* find command using IFS instead

* 🎉 IFS fix worked - escaped quotes for git mv

* protetc each word in git mv ..

* filename exists in lower cases - renamed

* 🎉 git push enabled

* updating DIRECTORY.md

* git pull & then push

* formatting filenames d7af6fdc8c

* formatting source-code for d7af6fdc8c

* remove allman break before braces

* updating DIRECTORY.md

* added missing comma lost in previous commit

* orchestrate all workflows

* fix yml indentation

* force push format changes, add title to DIRECTORY.md

* pull before proceeding

* reorganize pull commands

* use master branches for actions

* rename .cc files to .cpp

* added class destructor to clean up dynamic memory allocation

* rename to awesome workflow

* commented whole repo cpplint - added modified files lint check

* removed need for cpplint

* attempt to use actions/checkout@master

* temporary: no dependency on cpplint

* formatting filenames 153fb7b8a5

* formatting source-code for 153fb7b8a5

* updating DIRECTORY.md

* fix diff filename

* added comments to the code

* added test case

* formatting source-code for a850308fba

* updating DIRECTORY.md

* added machine learning folder

* added adaline algorithm

* updating DIRECTORY.md

* fixed issue [LWG2192](https://cplusplus.github.io/LWG/issue2192) for std::abs on MacOS

* add cmath for same bug: [LWG2192](https://cplusplus.github.io/LWG/issue2192) for std::abs on MacOS

* formatting source-code for f8925e4822

* use STL's inner_product

* formatting source-code for f94a330594

* added range comments

* define activation function

* use equal initial weights

* change test2 function to predict

* activation function not friend

* previous commit correction

* added option for predict function to return value before applying activation function as optional argument

* added test case to classify points lying within a sphere

* improve documentation for adaline

* formatting source-code for 15ec4c3aba

* added cmake to geometry folder

* added algorithm include for std::max

* add namespace - machine_learning

* add namespace - statistics

* add namespace - sorting

* added sorting algos to namespace sorting

* added namespace string_search

* formatting source-code for fd69530515

* added documentation to string_search namespace

* feat: Add BFS and DFS algorithms to check for cycle in a directed graph

* Remove const references for input of simple types

Reason: overhead on access

* fix bad code

sorry for force push

* Use pointer instead of the non-const reference

because apparently google says so.

* Remove a useless and possibly bad Graph constuctor overload

* Explicitely specify type of vector during graph instantiation

* updating DIRECTORY.md

* find openMP before adding subdirectories

* added kohonen self organizing map

* updating DIRECTORY.md

* remove older files and folders from gh-pages before adding new files

* remove chronos library due to inacceptability by cpplint

* use c++ specific static_cast instead

* initialize radom number generator

* updated image links with those from CPP repository

* rename computer.... folder to numerical methods

* added durand kerner method for root computation for arbitrarily large polynomials

* fixed additional comma

* fix cpplint errors

* updating DIRECTORY.md

* convert to function module

* update documentation

* move openmp to main loop

* added two test cases

* use INT16_MAX

* remove return statement from omp-for loop and use "break"

* run tests when no input is provided and skip tests when input polynomial is provided

* while loop cannot have break - replaced with continue and check is present in the main while condition

* (1) break while loop (2) skip runs on break_loop instead of hard-break

* add documentation images

* use long double for errors and tolerance checks

* make iterator variable i local to threads

* add critical secions to omp threads

* bugfix: move file writing outside of the parallel loop
othersie, there is no gurantee of the order of roots written to file

* rename folder to data_structures

* updating DIRECTORY.md

* fix ambiguous symbol `size`

* add data_structures to cmake

* docs: enable tree view, add timestamp in footer, try clang assistaed parsing

* doxygen - open links in external window

* remove invalid parameter from function docs

* use HTML5 img tag to resize images

* move file to proper folder

* fix documentations and cpplint

* formatting source-code for aacaf9828c

* updating DIRECTORY.md

* cpplint: add braces for multiple statement if

* add explicit link to badges

* remove  duplicate line

Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com>

* remove namespace indentation

* remove file associations in settings

* add author name

* enable cmake in subfolders of data_structures

* create and link object file

* cpp lint fixes and instantiate template classes

* cpp lint fixes and instantiate template classes

Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com>

* cpplint - ignore `build/include`

Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com>

* disable redundant gcc compilation in cpplint workflow

Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com>

* template header files contain function codes as well and removed redundant subfolders

Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com>

* updating DIRECTORY.md

* remove semicolons after functions in a class

Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com>

* cpplint header guard style

Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com>

* remove semilon

Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com>

* added LU decomposition algorithm

Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com>

* added QR decomposition algorithm

Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com>

* use QR decomposition to find eigen values

Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com>

* updating DIRECTORY.md

* use std::rand for thread safety

Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com>

* move srand to main()

Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com>

* cpplint braces correction

Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com>

* updated eigen value documentation

Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com>

* fix matrix shift doc

Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com>

* rename CONTRIBUTION.md to CONTRIBUTING.md #836

* remove 'sort alphabetical order' check

* added documentation check

* remove extra paranthesis

* added gitpod

* added gitpod link from README

* attempt to add vscode gitpod extensions

* update gitpod extensions

* add gitpod extensions cmake-tools and git-graph

* remove gitpod init and add commands

* use init to one time install doxygen, graphviz, cpplint

* use gitpod dockerfile

* add ninja build system to docker

* remove configure task

* add github prebuild specs to gitpod

* disable gitpod addcommit

* update documentation for kohonen_som

* added ode solve using forward euler method

* added mid-point euler ode solver

* fixed itegration step equation

* added semi-implicit euler ODE solver

* updating DIRECTORY.md

* fix cpplint issues - lines 117 and 124

* added documentation to ode group

* corrected semi-implicit euler function

* updated docs and test cases better structure

* replace `free` with `delete` operator

* formatting source-code for f55ab50cf2

* updating DIRECTORY.md

* main function must return

* added machine learning group

* added kohonen som topology algorithm

* fix graph image path

* updating DIRECTORY.md

* fix braces

* use snprintf instead of sprintf

* use static_cast

* hardcode character buffer size

* fix machine learning groups in documentation

* fix missing namespace function

* replace kvedala fork references to TheAlgorithms

* fix bug in counting_sort

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Co-authored-by: Anmol3299 <mittalanmol22@gmail.com>
2020-06-19 21:34:56 +05:30

340 lines
11 KiB
C++

/**
* @file
* \brief Compute all possible approximate roots of any given polynomial using
* [Durand Kerner
* algorithm](https://en.wikipedia.org/wiki/Durand%E2%80%93Kerner_method)
* \author [Krishna Vedala](https://github.com/kvedala)
*
* Test the algorithm online:
* https://gist.github.com/kvedala/27f1b0b6502af935f6917673ec43bcd7
*
* Try the highly unstable Wilkinson's polynomial:
* ```
* ./numerical_methods/durand_kerner_roots 1 -210 20615 -1256850 53327946
* -1672280820 40171771630 -756111184500 11310276995381 -135585182899530
* 1307535010540395 -10142299865511450 63030812099294896 -311333643161390640
* 1206647803780373360 -3599979517947607200 8037811822645051776
* -12870931245150988800 13803759753640704000 -8752948036761600000
* 2432902008176640000
* ```
* Sample implementation results to compute approximate roots of the equation
* \f$x^4-1=0\f$:\n
* <img
* src="https://raw.githubusercontent.com/TheAlgorithms/C-Plus-Plus/docs/images/numerical_methods/durand_kerner_error.svg"
* width="400" alt="Error evolution during root approximations computed every
* iteration."/> <img
* src="https://raw.githubusercontent.com/TheAlgorithms/C-Plus-Plus/docs/images/numerical_methods/durand_kerner_roots.svg"
* width="400" alt="Roots evolution - shows the initial approximation of the
* roots and their convergence to a final approximation along with the iterative
* approximations" />
*/
#include <algorithm>
#include <cassert>
#include <cmath>
#include <complex>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>
#include <valarray>
#ifdef _OPENMP
#include <omp.h>
#endif
#define ACCURACY 1e-10 /**< maximum accuracy limit */
/**
* Evaluate the value of a polynomial with given coefficients
* \param[in] coeffs coefficients of the polynomial
* \param[in] x point at which to evaluate the polynomial
* \returns \f$f(x)\f$
**/
std::complex<double> poly_function(const std::valarray<double> &coeffs,
std::complex<double> x) {
double real = 0.f, imag = 0.f;
int n;
// #ifdef _OPENMP
// #pragma omp target teams distribute reduction(+ : real, imag)
// #endif
for (n = 0; n < coeffs.size(); n++) {
std::complex<double> tmp =
coeffs[n] * std::pow(x, coeffs.size() - n - 1);
real += tmp.real();
imag += tmp.imag();
}
return std::complex<double>(real, imag);
}
/**
* create a textual form of complex number
* \param[in] x point at which to evaluate the polynomial
* \returns pointer to converted string
*/
const char *complex_str(const std::complex<double> &x) {
#define MAX_BUFF_SIZE 50
static char msg[MAX_BUFF_SIZE];
std::snprintf(msg, MAX_BUFF_SIZE, "% 7.04g%+7.04gj", x.real(), x.imag());
return msg;
}
/**
* check for termination condition
* \param[in] delta point at which to evaluate the polynomial
* \returns `false` if termination not reached
* \returns `true` if termination reached
*/
bool check_termination(long double delta) {
static long double past_delta = INFINITY;
if (std::abs(past_delta - delta) <= ACCURACY || delta < ACCURACY)
return true;
past_delta = delta;
return false;
}
/**
* Implements Durand Kerner iterative algorithm to compute all roots of a
* polynomial.
*
* \param[in] coeffs coefficients of the polynomial
* \param[out] roots the computed roots of the polynomial
* \param[in] write_log flag whether to save the log file (default = `false`)
* \returns pair of values - number of iterations taken and final accuracy
* achieved
*/
std::pair<uint32_t, double> durand_kerner_algo(
const std::valarray<double> &coeffs,
std::valarray<std::complex<double>> *roots, bool write_log = false) {
long double tol_condition = 1;
uint32_t iter = 0;
int n;
std::ofstream log_file;
if (write_log) {
/*
* store intermediate values to a CSV file
*/
log_file.open("durand_kerner.log.csv");
if (!log_file.is_open()) {
perror("Unable to create a storage log file!");
std::exit(EXIT_FAILURE);
}
log_file << "iter#,";
for (n = 0; n < roots->size(); n++) log_file << "root_" << n << ",";
log_file << "avg. correction";
log_file << "\n0,";
for (n = 0; n < roots->size(); n++)
log_file << complex_str((*roots)[n]) << ",";
}
bool break_loop = false;
while (!check_termination(tol_condition) && iter < INT16_MAX &&
!break_loop) {
tol_condition = 0;
iter++;
break_loop = false;
if (log_file.is_open())
log_file << "\n" << iter << ",";
#ifdef _OPENMP
#pragma omp parallel for shared(break_loop, tol_condition)
#endif
for (n = 0; n < roots->size(); n++) {
if (break_loop)
continue;
std::complex<double> numerator, denominator;
numerator = poly_function(coeffs, (*roots)[n]);
denominator = 1.0;
for (int i = 0; i < roots->size(); i++)
if (i != n)
denominator *= (*roots)[n] - (*roots)[i];
std::complex<long double> delta = numerator / denominator;
if (std::isnan(std::abs(delta)) || std::isinf(std::abs(delta))) {
std::cerr << "\n\nOverflow/underrun error - got value = "
<< std::abs(delta) << "\n";
// return std::pair<uint32_t, double>(iter, tol_condition);
break_loop = true;
}
(*roots)[n] -= delta;
#ifdef _OPENMP
#pragma omp critical
#endif
tol_condition = std::max(tol_condition, std::abs(std::abs(delta)));
}
// tol_condition /= (degree - 1);
if (break_loop)
break;
if (log_file.is_open()) {
for (n = 0; n < roots->size(); n++)
log_file << complex_str((*roots)[n]) << ",";
}
#if defined(DEBUG) || !defined(NDEBUG)
if (iter % 500 == 0) {
std::cout << "Iter: " << iter << "\t";
for (n = 0; n < roots->size(); n++)
std::cout << "\t" << complex_str((*roots)[n]);
std::cout << "\t\tabsolute average change: " << tol_condition
<< "\n";
}
#endif
if (log_file.is_open())
log_file << tol_condition;
}
return std::pair<uint32_t, long double>(iter, tol_condition);
}
/**
* Self test the algorithm by checking the roots for \f$x^2+4=0\f$ to which the
* roots are \f$0 \pm 2i\f$
*/
void test1() {
const std::valarray<double> coeffs = {1, 0, 4}; // x^2 - 2 = 0
std::valarray<std::complex<double>> roots(2);
std::valarray<std::complex<double>> expected = {
std::complex<double>(0., 2.),
std::complex<double>(0., -2.) // known expected roots
};
/* initialize root approximations with random values */
for (int n = 0; n < roots.size(); n++) {
roots[n] = std::complex<double>(std::rand() % 100, std::rand() % 100);
roots[n] -= 50.f;
roots[n] /= 25.f;
}
auto result = durand_kerner_algo(coeffs, &roots, false);
for (int i = 0; i < roots.size(); i++) {
// check if approximations are have < 0.1% error with one of the
// expected roots
bool err1 = false;
for (int j = 0; j < roots.size(); j++)
err1 |= std::abs(std::abs(roots[i] - expected[j])) < 1e-3;
assert(err1);
}
std::cout << "Test 1 passed! - " << result.first << " iterations, "
<< result.second << " accuracy"
<< "\n";
}
/**
* Self test the algorithm by checking the roots for \f$0.015625x^3-1=0\f$ to
* which the roots are \f$(4+0i),\,(-2\pm3.464i)\f$
*/
void test2() {
const std::valarray<double> coeffs = {// 0.015625 x^3 - 1 = 0
1. / 64., 0., 0., -1.};
std::valarray<std::complex<double>> roots(3);
const std::valarray<std::complex<double>> expected = {
std::complex<double>(4., 0.), std::complex<double>(-2., 3.46410162),
std::complex<double>(-2., -3.46410162) // known expected roots
};
/* initialize root approximations with random values */
for (int n = 0; n < roots.size(); n++) {
roots[n] = std::complex<double>(std::rand() % 100, std::rand() % 100);
roots[n] -= 50.f;
roots[n] /= 25.f;
}
auto result = durand_kerner_algo(coeffs, &roots, false);
for (int i = 0; i < roots.size(); i++) {
// check if approximations are have < 0.1% error with one of the
// expected roots
bool err1 = false;
for (int j = 0; j < roots.size(); j++)
err1 |= std::abs(std::abs(roots[i] - expected[j])) < 1e-3;
assert(err1);
}
std::cout << "Test 2 passed! - " << result.first << " iterations, "
<< result.second << " accuracy"
<< "\n";
}
/***
* Main function.
* The comandline input arguments are taken as coeffiecients of a
*polynomial. For example, this command
* ```sh
* ./durand_kerner_roots 1 0 -4
* ```
* will find roots of the polynomial \f$1\cdot x^2 + 0\cdot x^1 + (-4)=0\f$
**/
int main(int argc, char **argv) {
/* initialize random seed: */
std::srand(std::time(nullptr));
if (argc < 2) {
test1(); // run tests when no input is provided
test2(); // and skip tests when input polynomial is provided
std::cout << "Please pass the coefficients of the polynomial as "
"commandline "
"arguments.\n";
return 0;
}
int n, degree = argc - 1; // detected polynomial degree
std::valarray<double> coeffs(degree); // create coefficiencts array
// number of roots = degree - 1
std::valarray<std::complex<double>> s0(degree - 1);
std::cout << "Computing the roots for:\n\t";
for (n = 0; n < degree; n++) {
coeffs[n] = strtod(argv[n + 1], nullptr);
if (n < degree - 1 && coeffs[n] != 0)
std::cout << "(" << coeffs[n] << ") x^" << degree - n - 1 << " + ";
else if (coeffs[n] != 0)
std::cout << "(" << coeffs[n] << ") x^" << degree - n - 1
<< " = 0\n";
/* initialize root approximations with random values */
if (n < degree - 1) {
s0[n] = std::complex<double>(std::rand() % 100, std::rand() % 100);
s0[n] -= 50.f;
s0[n] /= 50.f;
}
}
// numerical errors less when the first coefficient is "1"
// hence, we normalize the first coefficient
{
double tmp = coeffs[0];
coeffs /= tmp;
}
clock_t end_time, start_time = clock();
auto result = durand_kerner_algo(coeffs, &s0, true);
end_time = clock();
std::cout << "\nIterations: " << result.first << "\n";
for (n = 0; n < degree - 1; n++)
std::cout << "\t" << complex_str(s0[n]) << "\n";
std::cout << "absolute average change: " << result.second << "\n";
std::cout << "Time taken: "
<< static_cast<double>(end_time - start_time) / CLOCKS_PER_SEC
<< " sec\n";
return 0;
}