Approximating square roots in java using the squeeze theorem - java

Hey guys this is for a homework assignment that is way over my head. My teacher is moving the class very quickly. This is my fourth program I have ever written in java, and I am looking for some advise. I need to find the approximate sqrt of a number to an error of EPSILON defined in my program. However, this needs to be accomplished using the squeeze theorem, and constantly updating my bounds. In java how does one update the values of variables fluidly when they are used throughout? Keep in mind my professor has not gotten to return values yet, so I do not think he intends for us to use them. Keep in mind I am quite the novice, but I have an open mind.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
final double EPSILON = .0000000001;
System.out.print("Enter a number to find its square root -> ");
double number = sc.nextDouble();
double low = 0;
double high = 0;
double midPoint = (low+high)/2;
high = number;
double midPointSqr = midPoint*midPoint;
if (number < 0) {
System.out.println("NaN");
} else {
while ((Math.abs(midPointSqr - number)) > EPSILON) {
{
if (number <= 1) {
low = 0;
if (midPointSqr > number)
{
midPoint = (high+low)/2;
high = high/2;
System.out.printf("%.6f, %.6f\n", low, high);
}
else
{
midPoint = (high+low)/2;
low = high/2;
System.out.printf("%.6f, %.6f\n", low, high);
}
} else {
low = 1;
if (midPointSqr > number)
{
midPoint = (high+low)/2;
high = high/2;
System.out.printf("%.6f, %.6f\n", low, high);
}
else
{
midPoint = (high+low)/2;
low = high/2;
System.out.printf("%.6f, %.6f\n", low, high);
}
}
}
}
}
}
}

you need to update midPointSqr variable whenever you update midpoint variable. So wherever you have assignment statements like
midPoint = <something>;
you should recopute your square right after that like this:
midPointSqr = midPoint * midPoint
Another alternarive is to use a function everywhere instead of using midPointSqr variable.
double getSqr(double value){
return value* value;
}
so whereever you are using midPointSqr variable replace it with following method code:
getSqr(midPoint)

Related

My code doesn't calculate min and max numbers

I'm trying to write a code which will show the highest, lowest, the difference of them and the average of inputted 30 numbers.
But its not working and is showing the same result for both min and max numbers. Here is the code.
public class aa {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] daystemp = new int[30];
int i = 0;
int dayHot = 0;
int dayCold = 0;
while(i < daystemp.length){
daystemp[i] = input.nextInt();
i++;
}
int maxTemp = daystemp[0];
while (i < daystemp.length) {
if (daystemp[i] > maxTemp) {
maxTemp = daystemp[i];
dayHot = i + 1;
i++;
}
}
System.out.println(maxTemp);
int minTemp = daystemp[0];
while (i < daystemp.length) {
if (daystemp[i] < minTemp) {
minTemp = daystemp[i];
dayCold = i + 1;
i++;
}
}
System.out.println(minTemp);
int diff = maxTemp - minTemp;
System.out.println("The difference between them is"+diff);
double sum = 0;
while(i < daystemp.length) {
sum += daystemp[i];
i++;
}
double average = sum / daystemp.length;
System.out.println("Average was"+average);
}
}
After the first loop (the input loop), i value is daystemp.length (i.e. 30).
It's never reset to 0. So each while loop condition is false.
Add i=0 before the loops and do i++outside the ifblocks or your code will never end.
example:
i=0;
int maxTemp = daystemp[0];
while (i < daystemp.length) {
if (daystemp[i] > maxTemp) {
maxTemp = daystemp[i];
dayHot = i + 1;
}
i++;
}
A few notes about this solution:
By declaring the cumulative total double, no casting is required.
Because Java knows you want to convert int to double automatically if you assign an int to a declared double. Similary the fact that you want to express a result as double is implied when dividing a double by an int, such as when the average is taken. That avoids a cast also. If you had two ints and you wanted to produce a double you'd need to cast one or more of them, or in cases like a print statement where the compiler can't deduce the optimal type for the parameter, you'd need to explicitly cast to covert an int value to a double.
Not sure what OS you're running this on. The ideal situation would be to make it work on all platforms without requiring people type a magic word to end input (because how tacky). The easiest way to end input is to use the OS-specific end of input (end of file) key combination, and for Linux it's CTRL/D, which is how I explained it in the prompt. On another OS with a different end of input sequence you could just change the prompt. The trickiest would be if it is supposed to be truly portable Java. In that case I'd personally investigate how I could figure out the OS and/or End of File character or key combination on the current OS and modify the prompt to indicate to end input with whatever that is. That would be a bit of and advanced assignment but a very cool result.
Example illustrates use of a named constant to determine the array and is used limit the amount of input (and could be used to limit loop count of for loops accessing the array).
By setting the min and max to very high and low values respectively (notice the LOW value assigned to max and HIGH value assigned to min, those ensure the first legit temp entered will set the min and max and things will go from there).
Temperature Maximum, Minimum, Average and Difference Calculator
import java.util.Scanner;
public class TemperatureStats {
final static int MAX_DAYS = 31;
public static void main(String[] args) {
int[] dayTemps = new int[MAX_DAYS];
double cumulativeTemp = 0.0;
int minTemp = 1000, maxTemp = -1000;
Scanner input = new Scanner(System.in);
System.out.println("Enter temps for up to 1 month of days (end with CTRL/D):");
int entryCount = 0;
while (input.hasNextInt() && entryCount < MAX_DAYS)
dayTemps[entryCount++] = input.nextInt();
/* Find min, max, cumulative total */
for (int i = 0; i < entryCount; i++) {
int temp = dayTemps[i];
if (temp < minTemp)
minTemp = temp;
if (temp > maxTemp)
maxTemp = temp;
cumulativeTemp += temp;
}
System.out.println("High temp. = " + maxTemp);
System.out.println("Low temp. = " + minTemp);
System.out.println("Difference = " + (maxTemp - minTemp));
System.out.println("Avg temp. = " + cumulativeTemp / entryCount);
}
}

Recursion Question - Java - Minimum number of golf shots

I am trying to calculate the minimum number of shots I need to take based on a given number of club lengths. You can also think of it as the minimum number of coins needed for a given change.
My code is
public static int golf(int holeLength, int[] clubLengths)
{
return golf(holeLength, clubLengths, 0);
}
public static int golf(int holeLength, int[] clubLengths, int shots)
{
if(holeLength==0)
shots+=0;
else if(holeLength<0)
shots=-1;
else
{
for(int i = 0; i<clubLengths.length; i++)
{
return golf(holeLength-clubLengths[i], clubLengths, shots+1);
}
}
return shots;
}
The issue here is that it only seems to give an answer based on the first number on the array. So for example, if I had {25,50,100} and I wanted to get to 100. Obviously, there is only a minimum of one shot required, yet the program will only calculate it using 25 and say 4. Similarly, if the first number is 21, then it will just give a stackoverflow.
Here is what is happening in your code: when the function runs the first loop, it gets the first element in clubLengths and returns right away without going to the next loop. You need to go through each possible clubs to use.
Here is my recursive solution:
Go through each club.
You can choose to use current club and use it again,
Or you can choose to use current club and use next club,
Or you can choose not to use current club and use next club.
I can implement this the following way:
public static int golf(int holeLength, int[] clubLengths) {
int[][] dp = int[clubLengths.length()][holeLength+1];
return golf(holeLength, clubLengths, 0, dp);
}
private static int golf(int holeLength, int[] clubLengths, int ind, int[][] dp) {
if (holeLength == 0) return 0;
if (holeLength < 0) return -1;
if (ind >= clubLengths.length()) return -1;
if (dp[ind][holeLength] != 0) return dp[ind][holeLength];
int rec1 = golf(holeLength-clubLengths[ind], clubLengths, ind, dp);
if (rec1 == -1) rec1 = Integer.MAX_VALUE;
else rec1++;
int rec2 = golf(holeLength-clubLengths[ind], clubLengths, ind+1, dp);
if (rec2 == -1) rec2 == Integer.MAX_VALUE;
else rec2++;
int rec3 = golf(holeLength, clubLengths, ind+1, dp);
if (rec3 == -1) rec3 = Integer.MAX_VALUE;
int result = Math.min(rec1, rec2);
result = Math.min(result, rec3);
if (result == Integer.MAX_VALUE) result = -1;
dp[ind][holeLength] = result;
return result;
}
Along with recursion, I have also added dp to optimize time complexity. As a result, the time complexity of my solution would be O(k*n) where k is holeLength and n is number of elements in clubsLengths. If you do not want dp and want just pure recursion, you can just remove all usages of dp from above and the code will still work, but slower.

power function to find the power where exponent is in decimal and less than 1

I was trying to create a program that finds the power of a real number . The problem is that exponent is in decimal and less than 1 but not negative.
suppose we have to find the power of
50.76
what i really tried was i wrote 0.76 as 76/100 and it would be 576/100
and after that i wrote
here is the code if you want to see what i did
public class Struct23 {
public static void main(String[] args) {
double x = 45;
int c=0;
StringBuffer y =new StringBuffer("0.23");
//checking whether the number is valid or not
for(int i =0;i<y.length();i++){
String subs = y.substring(i,i+1);
if(subs.equals(".")){
c=c+1;
}
}
if(c>1){
System.out.println("the input is wrong");
}
else{
String nep= y.delete(0, 2).toString();
double store = Double.parseDouble(nep);
int length = nep.length();
double rootnum = Math.pow(10, length);
double skit = power(x,store,rootnum);
System.out.println(skit);
}
}
static double power(double x,double store,double rootnum){
//to find the nth root of number
double number = Math.pow(x, 1/rootnum);
double power = Math.pow(number, store);
return power;
}
}
the answer would come but the main problem is that i cannot use pow function to do that
i can't also use exp() and log() functions.
i can only use
+
-
*
/
help me suggest your ideas .
thanks in advance
def newtons_sqrt(initial_guess, x, threshold=0.0001):
guess = initial_guess
new_guess = (guess+float(x)/guess)/2
while abs(guess-new_guess) > threshold :
guess=new_guess
new_guess = (guess+float(x)/guess)/2
return new_guess
def power(base, exp,threshold=0.00001):
if(exp >= 1): # first go fast!
temp = power(base, exp / 2);
return temp * temp
else: # now deal with the fractional part
low = 0
high = 1.0
sqr = newtons_sqrt(base/2,base)
acc = sqr
mid = high / 2
while(abs(mid - exp) > threshold):
sqr = newtons_sqrt(sqr/2.0,sqr)
if (mid <= exp):
low = mid
acc *= sqr
else:
high = mid
acc *= (1/sqr)
mid = (low + high) / 2;
return acc
print newtons_sqrt(1,8)
print 8**0.5
print power(5,0.76)
print 5**0.76
I reapropriated most of this answer from https://stackoverflow.com/a/7710097/541038
you could also expound on newtons_sqrt to give newtons_nth_root ... but then you have to figure out that 0.76 == 76/100 (which im sure isnt too hard really)
you can convert your number to complex form of it and then use de Moivre' formula to compute the nth root of your number using your legal oprations.

Maximize function in Java

I followed an example about a Genetic Algorithm in Java. Although I understand the concept of this application, I do not understand how I would apply a formula of my choice and let the Genetic Algorithm find it's highest value with x (an Individual' gene).
I tried the following code, by having the fitness return the value of the formula as followed:
static int getFitness(Individual individual) {
int fitness = 0;
Integer x = Integer.parseInt(individual.toString(), 2);
fitness = calculateFormula(x);
return fitness;
}
public static int calculateFormula(int x) {
int result = (-x * x) + (7 * x);
return result;
}
But with the tutorial I followed, you are supposed to specify a solution at the beginning. But when I do this, it is going to search for that solution and not the value of x that will return the highest result. By not specifying a solution, it will just end when it has found the gene representing 0.
So the question:
How would I apply a formula to the Genetic Algorithm, so it will look for the highest result of the formula -x² + 7x?
By "specifying a solution" you probably mean the following function in the blog:
static int getMaxFitness() {
int maxFitness = solution.length;
return maxFitness;
}
Which is causing trouble in your case. The dumb solution:
static int getMaxFitness() {
return 12;
}
Now the algorithm will find 3 (00011 you only need 5 bits/genes to check 0 to 31) or 4 (00100) as it is supposed to.
For a more intelligent solution we have to look at the termination criteria:
int generationCount = 0;
while(myPop.getFittest().getFitness() < FitnessCalc.getMaxFitness()){
generationCount++;
System.out.println("Generation: "+generationCount+" Fittest: "+myPop.getFittest().getFitness());
myPop = Algorithm.evolvePopulation(myPop);
}
You could stop looking for a solution when there was no improvement for X generations:
int bestFitness = Integer.MIN_VALUE;
Individual bestIndividual = null;
int noImprovementCount = 0;
for (int generationCount = 1;; generationCount++) {
System.out.println("Generation: "+generationCount+" Fittest: "+myPop.getFittest().getFitness());
myPop = Algorithm.evolvePopulation(myPop);
if (bestFitness < myPop.getFittest().getFitness()) {
bestIndividual = myPop.getFittest();
bestFitness = bestIndividual.getFitness();
noImprovementCount = 0;
} else if (++noImprovementCount == 5) { // X = 5
break;
}
}

Finding max and min using divide and conquer approach

I know this is a silly question,but I'm not getting this at all.
In this code taken from http://somnathkayal.blogspot.in/2012/08/finding-maximum-and-minimum-using.html
public int[] maxMin(int[] a,int i,int j,int max,int min) {
int mid,max1,min1;
int result[] = new int[2];
//Small(P)
if (i==j) max = min = a[i];
else if (i==j-1) { // Another case of Small(P)
if (a[i] < a[j]) {
this.max = getMax(this.max,a[j]);
this.min = getMin(this.min,a[i]);
}
else {
this.max = getMax(this.max,a[i]);
this.min = getMin(this.min,a[j]); }
} else {
// if P is not small, divide P into sub-problems.
// Find where to split the set.
mid = (i + j) / 2;
// Solve the sub-problems.
max1 = min1 = a[mid+1];
maxMin( a, i, mid, max, min );
maxMin( a, mid+1, j, max1, min1 );
// Combine the solutions.
if (this.max < max1) this.max = max1;
if (this.min > min1) this.min = min1;
}
result[0] = this.max;
result[1] = this.min;
return result;
}
}
Let's say the array is 8,5,3,7 and we have to find max and min,
Initial values of max and min=arr[0]=8;
First time list will be divided into 8,5
We call MaxMin with max=8 and min=8,since i==j-1,we will get max=8,min=5,
Next time list will be divided into [3,7],
min1=max1=arr[mid+1]=3,
We call MaxMin with max=3 and min=3.Since i is equal to j-1,we will get max=7,min=3,
Next the comparison is performed between max1,max and min1,min ,
Here is my confusion,
The values of max and max1 here is 8 and 7 respectively,but how???
We have not modified max1 anywhere,then how it will have a value 7,
As per my understanding,we had called MaxMin with max=3 and min=3 and then updated max=7 and min=3,but we had not returned these updated values,then how the values of max1 and min1 got updated,
I'm stuck at this,please explain.
Thanks.
It looks like you are updating 2 external values (not in this function) which are this.min and this.max
All you do is splitting in pieces of 1 or 2 elements and then update this.min and this.max, so you could also directly scan the array and check all int value for min/max. This is not really doing divide and conquer.
Here is a solution that really use divide and conquer :
public int[] maxMin(int[] a,int i,int j) {
int localmin,localmax;
int mid,max1,min1,max2,min2;
int[] result = new int[2];
//Small(P) when P is one element
if (i==j) {
localmin = a[i]
localmax = a[i];
}
else {
// if P is not small, divide P into sub-problems.
// where to split the set
mid = (i + j) / 2;
// Solve the sub-problems.
int[] result1 = maxMin( a, i, mid);
int[] result2 = maxMin( a, mid+1, j);
max1 = result1[0];
min1 = result1[1];
max2=result2[0];
min2=result2[1];
// Combine the solutions.
if (max1 < max2) localmax = max2;
else localmax=max1;
if (min1 < min2) localmin = min1;
else localmin=min2;
}
result[0] = localmax;
result[1] = localmin;
return result;
}
Frankly that blogger's code looks like a mess. You should have no confidence in it.
Take is this line early on:
if (i==j) max = min = a[i];
The values passed INTO the function, max and min, aren't ever used in this case, they are just set, and then lost forever. Note also if this line runs, the array result is neither set nor returned. (I would have thought that the compiler would warn that there are code paths that don't return a value.) So that's a bug, but since he never uses the return value anywhere it might be harmless.
The code sometimes acts like it is returning values through max and min (can't be done), while other parts of the code pass back the array result, or set this.max and this.min.
I can't quite decide without running it if the algorithm will ever return the wrong result. It may just happen to work. But its a mess, and if it were written better you could see how it worked with some confidence. I think the author should have written it in a more purely functional style, with no reliance on external variables like this.min and this.max.
Parenthetically, I note that when someone asked a question in the comments he replied to the effect that understanding the algorithm was the main goal. "Implementation [of] this algorithm is very much complex. For you I am updating a program with this." Gee, thanks.
In short, find a different example to study. Lord of dark posted a response as I originally wrote this, and it looks much improved.
Code
import java.util.Random;
public class MinMaxArray {
private static Random R = new Random();
public static void main(String[] args){
System.out.print("\nPress any key to continue.. ");
try{
System.in.read();
}
catch(Exception e){
;
}
int N = R.nextInt(10)+5;
int[] A = new int[N];
for(int i=0; i<N; i++){
int VAL = R.nextInt(200)-100;
A[i] = VAL;
}
Print(A);
Pair P = new Pair(Integer.MIN_VALUE, Integer.MAX_VALUE);
P = MinMax(A, 0, A.length-1);
System.out.println("\nMin: " + P.MIN);
System.out.println("\nMax: " + P.MAX);
}
private static Pair MinMax(int[] A, int start, int end) {
Pair P = new Pair(Integer.MIN_VALUE, Integer.MAX_VALUE);
Pair P_ = new Pair(Integer.MIN_VALUE, Integer.MAX_VALUE);
Pair F = new Pair(Integer.MIN_VALUE, Integer.MAX_VALUE);
if(start == end){
P.MIN = A[start];
P.MAX = A[start];
return P;
}
else if(start + 1 == end){
if(A[start] > A[end]){
P.MAX = A[start];
P.MIN = A[end];
}
else{
P.MAX = A[end];
P.MIN = A[start];
}
return P;
}
else{
int mid = (start + (end - start)/2);
P = MinMax(A, start, mid);
P_ = MinMax(A, (mid + 1), end);
if(P.MAX > P_.MAX){
F.MAX = P.MAX;
}
else{
F.MAX = P_.MAX;
}
if(P.MIN < P_.MIN){
F.MIN = P.MIN;
}
else{
F.MIN = P_.MIN;
}
return F;
}
}
private static void Print(int[] A) {
System.out.println();
for(int x: A){
System.out.print(x + " ");
}
System.out.println();
}
}
class Pair{
public int MIN, MAX;
public Pair(int MIN, int MAX){
this.MIN = MIN;
this.MAX = MAX;
}
}
Explanation
This is the JAVA code for finding out the MIN and MAX value in an Array using the Divide & Conquer approach, with the help of a Pair class.
The Random class of JAVA initializes the Array with a Random size N ε(5, 15) and with Random values ranging between (-100, 100).
An Object P of the Pair class is created which takes back the return value from MinMax() method. The MinMax() method takes an Array (A[]), a Starting Index (start) and a Final Index (end) as the Parameters.
Working Logic
Three different objects P, P_, F are created, of the Pair class.
Cases :-
Array Size -> 1 (start == end) : In this case, both the MIN and the MAX value are A[0], which is then assigned to the object P of the Pair class as P.MIN and P.MAX, which is then returned.
Array Size -> 2 (start + 1 == end) : In this case, the code block compares both the values of the Array and then assign it to the object P of the Pair class as P.MIN and P.MAX, which is then returned.
Array Size > 2 : In this case, the Mid is calculated and the MinMax method is called from start -> mid and (mid + 1) -> end. which again will call recursively until the first two cases hit and returns the value. The values are stored in object P and P_, which are then compared and then finally returned by object F as F.MAX and F.MIN.
The Pair Class has one method by the same name Pair(), which takes 2 Int parameters, as MIN and MAX, assigned to then as Pair.MIN and Pair.MAX
Further Links for Code
https://www.techiedelight.com/find-minimum-maximum-element-array-minimum-comparisons/
https://www.enjoyalgorithms.com/blog/find-the-minimum-and-maximum-value-in-an-array

Categories

Resources