Created
October 13, 2018 20:47
-
-
Save racecraftr/bbdee2f5bab098050976ceb4af565b28 to your computer and use it in GitHub Desktop.
Code for calculating a square root on processing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner;// this is to get the user input | |
String input = ""; | |
int num = 0; | |
void setup() { | |
size(400,200);// click on the screen to start up the program | |
intro(); | |
} | |
void draw() { | |
} | |
void keyPressed() { | |
if( key >= '0' && key <= '9') { | |
if(input.length() < 8) {// it should be 7 digits or less | |
input += key; | |
print(key); | |
} | |
else { | |
println("done! press enter!"); | |
} | |
} | |
else if(key == '\n'){ | |
num = Integer.parseInt(input); | |
input = ""; | |
println(" we'll find sqrt for: " + num); | |
findSqrt(num); | |
} | |
} | |
void intro() { | |
println("\nWhat is the integer that you want to find the square root of?"); | |
} | |
void findSqrt(float num) { | |
float lf = 0; | |
float rt = num; | |
float prev = 0; | |
float root = 0; | |
for(int i = 0; i<1000; i++){// here are the rules for calculating the square root | |
root = (lf + rt)/2;// this states that 0 + the number /2 = the root (the calculation) | |
if((root * root) == num) { | |
break;// if the root^2 is the number that you are trying to find the square root of, it breaks off from the process | |
} | |
else if((root * root) > num) { | |
rt = root;// root^2 > num, then the greater range of the calculation is the root | |
} | |
else { | |
lf = root; //root^2 < num, then the smaller range of the calculation is the root | |
} | |
if(prev == root){ | |
break; // only works if num == 0 | |
} | |
else { | |
prev = root; | |
} | |
println("iter["+i+"]("+lf+","+rt+"):" + root); | |
} | |
println(" value of root["+root+"] squared is: " + (root * root));// prints the true root | |
intro(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment