-
Notifications
You must be signed in to change notification settings - Fork 0
/
08-e05.c
41 lines (25 loc) · 869 Bytes
/
08-e05.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// square root function (Newton–Raphson method), 08-e04 modified
#include <stdio.h>
float absoluteValue(float x) { // calculate absolute value
if (x < 0) x = -x;
return x;
}
float squareRoot(float x, const float epsilon) { // calculate square root
float guess = 1.0;
if (x < 0) { // check for negative numbers in case of user input
printf("negative number\n");
return -1.0;
}
while (absoluteValue(1 - ((guess * guess) / x)) >= epsilon) {
guess = (x / guess + guess) / 2.0;
printf("%f\n", guess);
}
return guess;
}
int main(void) {
const float epsilon = .00001;
printf("square root of 2.0 = %f\n", squareRoot(2.0, epsilon));
printf("square root of 144.0 = %f\n", squareRoot(144.0, epsilon));
printf("square root of 17.5 = %f\n", squareRoot(17.5, epsilon));
return 0;
}