Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(JAVA) Write code that compares the speed of your MyMath.sqrt with Math.sqrt in

ID: 3874725 • Letter: #

Question

(JAVA) Write code that compares the speed of your MyMath.sqrt with Math.sqrt in the way specified below. This code should go into the public static member function named main with return type void.

Using a loop, evaluate Math.sqrt on 10, 000, 000 random numbers between 0 and 100. These random numbers should be generated by calling 100*Math.random(). Measure the time it takes to complete this task using System.currentTimeMillis. Do the same with MyMath.sqrt. You may want to consult: https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#currentTimeMillis()

This time measurement includes the time it takes to generate the random numbers. With a separate loop, measure the time it takes to generate the random numbers without evaluating the square root. Putting these measurement together, output, to the command line, the average execution time per evaluation of the two square root functions with the execution time of the random number generation subtracted out.

You will see that Math.sqrt is far superior over MyMath.sqrt. This is to be expected since standard math functions like Math.sqrt are implemented and optimized by a group of experts over many hours.

Explanation / Answer

Below is the required code,

The time to generate and evaluate 1 million numbers will be longer and will depend on the processing speed

class MyMath{

static double sqrt(int n) {

// This is the user defined sqrtfunction , put your sqrt function here below is a sample function for square root

double t;

double sr = n / 2;

do {

t = sr;

sr = (t + (n / t)) / 2;

} while ((t - sr) != 0);

return sr;

}}

public class MathFun {

public static void main(String[] args) {

// TODO Auto-generated method stub

int millionRandomNums[] = new int[1000000];

int i;

long timeBeforeNumbers = System.currentTimeMillis();

for(i=0;i<1000000;i++)

{

millionRandomNums[i]=(int)(100*Math.random());

}

long timeafterNumbers = System.currentTimeMillis();

  

  

for(i=0;i<1000000;i++)

{

Math.sqrt(millionRandomNums[i]);

}

long timeStd = System.currentTimeMillis();

for(i=0;i<1000000;i++)

{  

MyMath.sqrt(millionRandomNums[i]);

}

long timeMyF = System.currentTimeMillis();

  

  

System.out.println("Time Taken to Generate Random Numbers : " + (timeafterNumbers-timeBeforeNumbers));

System.out.println("Time Taken By Math.sqrt per evaluation : " +((timeStd-timeafterNumbers)/1000000));

System.out.println("Time Taken By MyMath.sqrt per evaluation : " + ((timeMyF-timeStd)/1000000));

  

  

}

}