Monday, April 15, 2013

How to calculate the square root of a number using simple Java

Overview:
For a simple problem of calculating the square root of a number, I will lay out a simple algorithm that can be applied in any language without too much difficulty. Since I am focusing on Java, all code snippets will be coded with Java. The project will also be posted.

What you may need:
To create and compile your code, download a Java IDE (Integrated Development Environment) like NetBeans or Eclipse. If you would like an easy to follow self paced instruction, check out the Youtube playlist from Stanford University. I suggest lectures 4 through 8.

Problem statement:
Without getting into too much theoretical mathematics, the mathematical solution to the equation:

is

Where c is the number you want to calculate the square root of and x is the solution that you will seek. The equation does not intuitively give you a methodology but  we can use the first equation to see how close we are to finding the solution.

Assumptions:
The assumptions made here is based off advance algebra/pre-calculus concepts. For the purposes of this demonstration, the assumptions listed below will hold true in all cases.
  • c can not be a negative number
  • if the value of c is 0, the value of x is 0
  • if the value of c is 1, then the value of x is 1
  • if c is greater than 1, then the value of x will be less than c but greater than 1
  • if c is between 0 and 1, then the value of x will be greater than c but less than 1
Equation for assumption in bullet #4

Equation for assumption in bullet #5




Proposed algorithm:
For any problem you want to resolve with code, you need to build an algorithm. What this means is you need a stepwise method to solve your problem.
My approach is first list your known constants and assumptions. This is something that can be coded in the early stages of the code. Next determine a logical process for the code to follow. The best way to look at this is building a flow chart as shown below.
Sample Flow of Program

Once you have determined your process flow, think about any sub-processes or contained algorithms that you will need. If you notice in my drawing, I have "Find x between c and 1" located in one of the process boxes. Once you figure out how you will do that, you will just build another logical flow for that process. Your process building will end once you are at a point where you can determine if you have found x or a very close solution to x.

I will utilize a take on a method I learned in my Numerical Methods class in college called midpoint finding. Since I know that x will have to exists between 1 and c for both assumptions #4 and #5, I can look at the midpoint value between 1 and c and set that equal to my guess for x. If I square the value of my guess and it is larger than c, I look at the midpoint between my guess and 1 and repeat until I get a guess that is within some defined tolerance that I will define. Similarly, if I square the value of my guess and it is smaller than c, I look at the midpoint between my guess and c and repeat until I reach a desired x. I will lay out the details of how this is done a little later because you may want to switch back and forth between smaller and larger depending on how small your tolerance is set to.


To solve the current problem at hand, I propose we use the following logic: (represent with graphics)
1) Gather user input and store to a variable I will call valueOfC which will be the value of c in the equation.
User Input

2) Compare valueOfC to each assumption
    a) If the valueOfC is less than 0 go to the output part of the program and tell the user "Can not calculate value"

    b) If the valueOfC is equal to 0, set a variable call numberOfIterations to 1 and guessValueOfX equal to 0 go to the output part of the program and tell the user "The Square Root of 0 is 0. It took 1 iteration to calculate".

   c) If the valueOfC is equal to 1, set a variable call numberOfIterations to 1 and guessValueOfX equal to 0 go to the output part of the program and tell the user "The Square Root of 1 is 1. It took 1 iteration to calculate".
   d) If the valueOfC is between 0 and 1, set a variable call rangeMax equal to 1, numberOfIterations to 1, rangeMin equal to valueOfC, and the guessValueOfX to the midpoint between rangeMax and rangeMin. I will send the variables valueOfC, guessValueOfX, rangeMax, and rangeMin to the goal seek algorithm.
   e) If the valueOfC is greater than 1, set a variable call rangeMax equal to valueOfCnumberOfIterations to 1, rangeMin equal to 1, and the guessValueOfX to the midpoint between rangeMax and rangeMin. I will send the variables valueOfC, guessValueOfX, rangeMax, and rangeMin to the goal seek algorithm.
3) Goal seek to find final answer
    a) Determine how close your guess is to the searched value for x. I will build the seek algorithm based on the following equations:

How to determine if you have solved the problem


We square the value of guessValueOfX and subtract valueOfC and set that equal to a variable called errorValue. I will then take the absolute value of errorValue (the number without the negative sign if the variable comes out less than 0) and set it equal to a variable called goalFind. goalFind can be compared to a tolerance constant (toleranceCheck), which I will set to 0.0001 (.01%). To refine our guess value, there is three possible outcomes for errorValue and goalFind
         i) If errorValue is less than 0 and goalFind is greater than toleranceCheck, then set rangeMax equal to guessValueOfX and add 1 to the numberOfIterations, set guessValueOfX equal to the midpoint between rangeMax and rangeMin. Go back to the start of goal seek algorithm.
         ii) If errorValue is greater than 0 and goalFind is greater than toleranceCheck, then set rangeMin equal to guessValueOfX and add 1 to the numberOfIterations, set guessValueOfX equal to the midpoint between rangeMax and rangeMin. Go back to the start of goal seek algorithm.
        iii) If goalFind is less than or equal to toleranceCheck go to program output telling the user the final value of guessValueOfX and the number of iterations it took to get there.

How to build this program:
For demonstration purposes I will utilize Eclipse IDE. You can download the program at the Stanford Eclipse link or a Google search for Eclipse. I will utilize the Console Java window so download the acm library file from the Java Task Force page or Google search acm.jar.

This blog will be the only time I will go step by step on project creation and code generation.

Once you have Eclipse open, you want to create a new Java project:

Create New Java Project

Name your project

I named the project SquareRootCalculator. Click Next to move on to the settings for your project. Click on the Libraries tab and click Add External JARs... 

Library tab



Add the acm.jar file



Once the acm library file is added, create a class file by right clicking the project name. This will be the file where your code will be created.

Create Class File
 I named the class file MySquareRootCalculator
Name your class file

You will now have a blank program with one line of code:
public class MySquareRootCalculator {

}
Initial code

Above the first line of code, we need to add an import statement which would bring up the console window:
import acm.program.*;

Import acm.program

After the import acm.program is added to your code, you have to add the text "extends ConsoleProgram" after MySquareRootCalculator

Extending to ConsoleProgram

Below the public class portion of the code, the following code needs to be added:
public void run() {

}

Establishing run method

Now you are ready to actually implement the program.

Between import acmprogram.*; and public class, you can make comments regarding the code using either "//" to make a line a comment line (portion of the code that is used for note taking only, "/* */" to make a comment block of code that will allow you to put comments for multiple lines between the * or "/** */" to make a special set of comments called Javadoc comments. I will add an error suppression piece of code because of serialization. You can read more at this Google link.

Between public class and the run method, I will define our variables and constants.

Variables and constants


In our run method is where I will put the guts of the code. All the algorithms will be built in between the run method's { }s.
Here is a quick snapshot of the code:
You can find the full project at this link.


Thank you for reading. The next blog will be about Code Optimization.
Syd

No comments:

Post a Comment