Last active
February 15, 2022 21:43
-
-
Save MathiasYde/847edbdcf1efc3601a5647779fec92b0 to your computer and use it in GitHub Desktop.
C++ implementation of Newton Raphson
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <chrono> | |
#include "math.h" | |
#include <tuple> | |
#include <vector> | |
#include <set> | |
#define printl(o) std::cout << o << std::endl; | |
#define print(o) std::cout << o; | |
#define number long double | |
number f(number x) { | |
// return 125*x; | |
x -= 150; | |
return pow(x, 3)-cos(x); | |
} | |
number slope(number x) { | |
number offset = 0.0001; | |
number halfoffset = offset / 2; | |
number x1 = x - halfoffset; | |
number x2 = x + halfoffset; | |
return (f(x2)-f(x1))/(x2-x1); | |
} | |
std::vector<number> solve(number x) { | |
std::vector<number> xs{}; | |
while (true) { | |
number x = (xs.size() == 0) ? rand() % 512 : xs.back(); | |
number x1 = x - f(x)/slope(x); | |
if (x1 == x) break; | |
xs.push_back(x1); | |
} | |
return xs; | |
} | |
int main() { | |
std::cout.precision(2048); | |
auto start = std::chrono::high_resolution_clock::now(); | |
std::tuple<int, int> domain {-256,256}; | |
std::set<number> possible_x {}; | |
for (int x = std::get<0>(domain); x < std::get<1>(domain); x++) { | |
possible_x.insert(solve(x).back()); | |
} | |
auto stop = std::chrono::high_resolution_clock::now(); | |
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(stop - start); | |
for (auto x : possible_x) { | |
print(x); | |
} | |
print("nanoseconds: "<< duration.count()); | |
} | |
// int main() { | |
// std::cout.precision(2048); | |
// std::tuple<int, int> domain {-256,256}; | |
// std::vector<std::tuple<int, std::vector<number>>> results; | |
// for (int x = std::get<0>(domain); x < std::get<1>(domain); x++) { | |
// //solve(x); | |
// results.push_back(std::make_tuple(x, solve(x))); | |
// } | |
// for (auto result : results) { | |
// print(std::get<0>(result)); | |
// print(":") | |
// for (auto x : std::get<1>(result)) { | |
// print(x); | |
// print(","); | |
// } | |
// printl(""); | |
// } | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment