Difficulty: ★ ★ ★ ☆
When I sought to write my own square root function back in 2020, I based it on a series of steps from the math.com website. I figured, “Hey! These guys are math nerds. They know their stuff.” Turns out, the ancient Babylonians beat them to the punch — and have a better method for calculating a square root.
When they weren’t conquering or being conquered, the Babylonians devised a method for calculating square roots that involves averages and division. I’ve seen it explained a few times, but the math nerds tend to make the procedure sound more complex than it is. Here’s my take:
- Start with the positive integer to find its square root. For example, five.
- Obtain the average of any two values greater-than and less-than what the square root might be. Continuing with the example, the average of 4 and 2 is 3.
- Divide the original positive integer by the result of Step 2: 5/3 = 1.666667.
- Repeat Steps 2 and 3 using the result of Step 3 as the less-than value in Step 2. So you continue with the average of 4 and 1.666667 = 2.833333, and then 5/2.833333, and so on.
Yes, even my version of the steps is confusing. So, Figure 1 attempts to illustrate the process, where Steps 1 and 2 (in the Figure) repeat a given number of times to obtain the square root of value root
.
In Figure 1, I removed the part about guessing the greater-than and less-than values. Instead, and in my exercise solution, I start the process by using the positive integer itself (root
) and 1.0. Then I repeat the steps from there, which may take longer but it codes more efficiently.
The more times you repeat Steps 1 and 2 (from Figure 1), the more precise the result. In my tests, seven times was adequate to obtain identical results as the C library’s sqrt() function, though some answers may suffer from the expected precision errors as floating-point calculations do.
Your task for this month’s Exercise is to write the function babylonian_sr(), which uses the Babylonian Method to calculate a square root. The function need not be recursive; I didn’t use recursion in my solution.
Here is a source code skeleton you can use for your solution:
2022_04_01-Lesson.c
#include <stdio.h> double babylonian_sr(double root) { } int main() { double pv,sr; printf("Enter a positive value: "); scanf("%lf",&pv); if( pv <= 0 ) return(1); sr = babylonian_sr(pv); printf("The square root of %.0f is %f\n", pv, sr ); return(0); }
This code prompts the user for a positive integer. This value is sent to the babylonian_sr() function, which calculates the square root to seven digits of precision. The value is returned from the function as a double, which is output in the main() function.
Here is a sample run of my solution:
Enter a positive value: 5
The square root of 5 is 2.236068
Please try this Exercise on your own before you peek at my solution.