Debian Codegraph @

Help/guide/tutorial/Step4/MathFunctions/MathFunctions.cxx

raw
1 // TODO5: Include <cmath>
2
3 #include <format>
4 #include <iostream>
5
6 namespace {
7 // a hack square root calculation using simple operations
8 double mysqrt(double x)
9 {
10 if (x <= 0) {
11 return 0;
12 }
13
14 double result = x;
15
16 // do ten iterations
17 for (int i = 0; i < 10; ++i) {
18 if (result <= 0) {
19 result = 0.1;
20 }
21 double delta = x - (result * result);
22 result = result + 0.5 * delta / result;
23
24 std::cout << std::format("Computing sqrt of {} to be {}\n", x, result);
25 }
26 return result;
27 }
28 }
29
30 namespace mathfunctions {
31 double sqrt(double x)
32 {
33 // TODO6: Check if TUTORIAL_USE_STD_SQRT is defined, if so use std::sqrt
34 // instead of mysqrt
35
36 return mysqrt(x);
37 }
38 }