In school we once had the “Heron algorithm”. It is used to get near the result of a square root.
If you for example try to get the square root of 25 you need the number whose square is 25. In this case it’s either 5 or -5 (But since the root is always positive the result is 5).
But what if you want to get the root of 3? And here comes the problem. It’s not that easy to find that root, especially without using the root function of the calculator, like it was the question we had. For this you use this algorithm.
And because it was too much work for me to invest the 10 to 15 minutes to do this homework and calculate everything step by step, I invested about 5 hours to build this program.
How it works:
You start with two numbers. The first one is the input number (the number you want the square root of) [let’s call it ‘in’ (constant)] and the second one is the number one [let’s call it ‘b’]. Additionally you save the value of ‘in’ in the variable ‘a’
- You get the number in between ‘a’ and ‘b’ and save it in the variable ‘a’ [a = (a+b) / 2]
- You divide ‘in’ by the new ‘a’ and set it to ‘b’ [b = in / a]
- You repeat number 1. and 2. as often as you want. (For small numbers up to 100, something like 5 repetitions should be enough)
- The user input of the number is a String so it has to be converted do an double to be usable. Then it’s passed as the start number to the algorithm
- The repetition count is an int and passed as an argument for the for loop. This defines how often the algorithm will be executed
- The “Create file” checkbox outputs a Boolean and decides in the and if the output should be printed to a file
- The output box is a not editable JTextarea
Heron Algorithm Calculator
Updated on 2018-10-30T22:44:26+00:00, by .