I'm relatively new to java, so I wouldn't be surprised if I'm missing something obvious here. Anyways, I made a code that finds the roots of a polynomial using the Bisection method. I thought the program was all well and dandy until I pasted it from notepad++ to command prompt, where I ended up getting a bunch of "class, interface, or enum expected" errors after compiling it using javac. Everything seems fine in the code itself, so I've deduced that I've made one of the following two errors: either something wrong occurred while I was copying and pasting into command prompt, or I actually did create an error in my code that I didn't catch. Could someone tell me just what I did wrong? It may be a minor fix, but I just don't know how to change it to get my code to work. Here's the code:
import java.util.*;
class Roots {
public static int degree;
public static double[] coArrayC;
public static double[] coArrayD;
public static int coeffVal;
public static void main( String[] args ){
double resolution = 0.01;
double tolerance = 0.0000001;
double threshold = 0.001;
double rightEndPt;
double leftEndPt;
int polyRootPointer = 0;
int diffRootPointer = 0;
boolean rootAns = false;
Scanner sc = new Scanner(System.in);
System.out.println();
System.out.print("Enter the degree: "); //prompts user to enter the correct degree of the polynomial
degree = sc.nextInt();
coeffVal = degree + 1; //the coefficient is one more than the number of degrees
System.out.print("Enter " + coeffVal + " coefficients: "); //adds in the value of the polynomial coefficient in to the line that prompts the user to specify which coefficients are in the function
double[] coefficients = new double[coeffVal]; //initialization of array, a bunch of doubles that represent the coefficients of the user's polynomial
coArrayC = new double[coeffVal]; //naming the array
double[] rootArray = new double[degree];//another array for the degrees of the polynomial
coArrayD = new double[coeffVal]; //and assigning it a name
for(int i = 0; i < coeffVal; i++) {
coefficients[i] = sc.nextDouble();
}
System.out.print("Enter the right and left endpoints, in that order: "); //prompts user to enter the interval limits
rightEndPt = sc.nextDouble();
leftEndPt = sc.nextDouble();
diff(coefficients); //calculates coefficients of derivative polynomial
for (double i = leftEndPt; i < rightEndPt-resolution; i = i + resolution){ //
if (isPositive(coArrayD, i) != isPositive(coArrayD, i+resolution) || isPositive(coArrayD, i) == 0) {
rootArrayDeriv[diffRootPointer] = findRoot(coArrayD, i, i+resolution, tolerance);
diffRootPointer++;
}
}
for (int i = 0; i < rootArrayDeriv.length; i++) {
double tempValue;
tempValue = poly(coefficients, rootArrayDeriv[i]);
tempValue = Math.abs(tempValue);
if (tempValue < threshold) {
rootArray[polyRootPointer] = rootArrayDeriv[i];
polyRootPointer++;
rootAns = true;
}
}
for (double i = leftEndPt; i < rightEndPt-resolution; i = i + resolution){
if (isPositive(coefficients, i) != isPositive(coefficients, i+resolution) || isPositive(coefficients, i) == 0) {
rootArray[polyRootPointer] = findRoot(coefficients, i, i+resolution, tolerance);
polyRootPointer++;
rootAns = true;
}
}
//Arrays.sort(rootArray); //sorts array from lowest to highest
if (rootAns == true) {
System.out.println("Sorry - no roots were found in the specified interval.");
}
}
} else {
for (int i = 0; i < rootArray.length; i++) {
if (rootArray[i] != 0.0) {
System.out.printf("Root found at %.5f\n :" Arrays.sort(rootArray[i])); //if roots are found, list them as an output, with five decimal places of accuracy
}
}
static double poly(double[] C, double x){
double polySum = 0;
coArrayC[0] = C[0];
for (int i = 1; i < coArrayC.length; i++){
coArrayC[i] = C[i]*(Math.pow(x, i)); //multiplies each coefficient by the designated power of X
}
for (int i = 0; i < coArrayC.length; i++){
polySum = polySum + coArrayC[i]; //accumulates the sum of of all the terms, after the coeff. were multiplied to their respective powers.
}
return(polySum);
}
static double[] diff(double[] C){
for (int i = 0; i < degree; i++){
coArrayD[i] = (i+1)*C[i+1]; //newly allocated array D containing coeff. of the polynomial that is the derivative of the polynomial with coeff. array C.
}
return(coArrayD);
}
static double findRoot(double[] C, double a, double b, double tolerance){ //using bisection method; similar to findRoot.java in cmps webpage.
double root = 0.0 , residual;
while ( Math.abs(b - a) > tolerance ) {
root = (a + b) / 2.0;
residual = poly(C, root);
if (poly(C, a) < 0 && poly(C, b) < 0) {
if (residual > 0)
b = root;
else
a = root;
} else if (poly(C, a) > 0 && poly(C, b) > 0) {
if (residual > 0)
a = root; //replace left endpoint
else
b = root; //replace right endpoint
}
}
return(root);
}
static int isPositive(double[] C, double a){
double endpointTempA;
endpointTempA = poly(C, a);
if (endpointTempA < 0) {
return(1);
} else if (endpointTempA > 0) {
return(2);
} else {
return(0);
}
}
}
You have two } too many here:
if (rootAns == true) {
System.out.println("Sorry - no roots were found in the specified interval.");
}
}
} else {
If you indent your code properly, it's easier to see these kinds of errors. Remove the two } that don't belong there:
if (rootAns == true) {
System.out.println("Sorry - no roots were found in the specified interval.");
} else {
There's also a missing , here, and you shouldn't pass a single double to Arrays.sort, but the whole array
System.out.printf("Root found at %.5f\n :"Arrays.sort(rootArray[i]));
Should be:
System.out.printf("Root found at %.5f\n :", Arrays.sort(rootArray));
And a missing }.
Instead of writing a whole program at once and then trying to compile it, write it little by little, and compile it each time you have for example a complete method. That way you avoid getting a mountain of little errors that confuse you.
Related
Nested radical constant is defined as:
I am writing a Java program to calculate the value of nested radical constant with 10^-6 precision and also print the number of iterations required to get to that precision. Here is my code:
public class nested_radical {
public nested_radical() {
int n = 1;
while ((loop(n) - loop(n - 1)) > 10e-6) {
n++;
}
System.out.println("value of given expression = " + loop(n));
System.out.println("Iterations required = " + n);
}
public double loop(int n) {
double sum = 0;
while (n > 0) {
sum = Math.sqrt(sum + n--);
}
return (sum);
}
public static void main(String[] args) {
new nested_radical();
}
}
This code does what it is supposed to but it is slow. What should I do to optimize this program? Can someone suggest another possible way to implement this program?
I also want to write a same kind of program in MATLAB. It would be great if someone could translate this program into MATLAB too.
I have made some changes in this code and now it stores the value of loop(n - 1) instead of computing it every time. Now this program seems much optimized than before.
public class nested_radical {
public nested_radical() {
int n = 1;
double x = 0, y = 0, p = 1;
while ( p > 10e-6) {
y=x; /*stored the value of loop(n - 1) instead of recomputing*/
x = loop(n);
p = x - y;
n++;
}
System.out.println("value of given expression = " + x);
System.out.println("Iterations required = " + n);
}
public double loop(int n) {
double sum = 0;
while (n > 0) {
sum = Math.sqrt(sum + n--);
}
return (sum);
}
public static void main(String[] args) {
new nested_radical();
}
}
I also successfully translated this code in MATLAB. Here is the code for MATLAB:
n = 1;
x = 0;
p = 1;
while(p > 10e-6)
y = x;
sum = 0;
m=n;
while (m > 0)
sum = sqrt(sum + m);
m = m - 1;
end
x = sum;
p = (x-y);
n = n + 1;
end
fprintf('Value of given expression: %.16f\n', x);
fprintf('Iterations required: %d\n', n);
I am trying to write a program which asks the user for a series of positive values and computes the mean and standard deviation of those values having the input stop when the user enters -1. I seem to have the average part down however. I can't seem to get the standard deviation.
So far this is what I have.
import java.util.Scanner;
public class HW0402
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double x;
double sum = 0;
double average = 0;
double dev = 0;
double var = 0;
double sqrx = 0;
int n = 0;
do
{
System.out.println("Enter positive values, enter -1 to end");
x = input.nextInt();
if (x == -1)
{
break;
}
sum += x;
n++;
average = sum / n;
sqrx += Math.pow(x-average,2);
var = sqrx / (n-1);
dev = Math.sqrt(var);
} while (x != -1);
System.out.println("Average: " + average);
System.out.println("Deviation: " + dev);
}
}
I seem to get odd results such as decimals when simply calculating sqrx += x- average
I'm new to java and haven't leaned alternatives to this problem, I would love it if someone pointed me in the right direction on what I should do, or explain what I did wrong.
Apologies ahead of time for any novice mistakes I made.
int n = 0;
int K = 0;
double Sum = 0;
double Sum_sqr = 0;
do {
System.out.println("Enter positive values, enter -1 to end");
x = input.nextInt();
if (x == -1)
{
break;
}
if ( n == 0 ) K = x;
n++;
Sum += (x - K);
Sum_sqr += (x - K) * (x - K);
} while (x != -1);
double mean = K + Sum / n;
double varPop = (Sum_sqr - (Sum*Sum)/n) / (n);
double varSample = (Sum_sqr - (Sum*Sum)/n) / (n-1);
double devPop = Math.sqrt(varPop);
double devSample = Math.sqrt(varSample);
Reference Wikipedia: Computing Shifted Data. Also, Population or Sample, makes a difference.
So I have a code that appears like it would have perfect formatting in Notepad++, but when I login to my Unix timeshare, open vim, and paste the code into the newly created file, it later has problems compiling. I keep getting "class, interface, or enum expected" errors, however my code appears to have the right amount of brackets and such. I've even tried using Filezilla to transfer my java file in to my unix folder, but I get the same errors. Does anybody else experience problems while transferring code from Notepad++ to Unix? If so, is there a way I can fix this? I've provided my code below; it is meant to find the roots of an entered polynomial using the bisection method:
import java.util.*;
class Roots {
public static int degree;
public static double[] coArrayC;
public static double[] coArrayD;
public static int coeffiNumb;
public static void main( String[] args ){
double resolution = 0.01;
double threshold = 0.001;
double tolerance = 0.0000001;
double rightEndPt;
double leftEndPt;
int polyRootPointer = 0;
int diffRootPointer = 0;
boolean rootAns = false;
Scanner sc = new Scanner(System.in);
System.out.println();
System.out.print("Enter the degree: ");
degree = sc.nextInt();
coeffiNumb = degree + 1;
System.out.print("Enter " + coeffiNumb + " coefficients: ");
double[] coefficients = new double[coeffiNumb];
coArrayC = new double[coeffiNumb];
double[] rootArray = new double[degree];
coArrayD = new double[coeffiNumb];
double[] rootArrayDeriv = new double[degree];
for(int i = 0; i < coeffiNumb; i++) {
coefficients[i] = sc.nextDouble();
}
System.out.print("Enter the lower and upper endpoints, in that order: ");
leftEndPt = sc.nextDouble();
rightEndPt = sc.nextDouble();
diff(coefficients);
for (double i = leftEndPt; i < rightEndPt-resolution; i = i + resolution){
if (isPositive(coArrayD, i) != isPositive(coArrayD, i+resolution) || isPositive(coArrayD, i) == 0) {
rootArrayDeriv[diffRootPointer] = findRoot(coArrayD, i, i+resolution, tolerance);
diffRootPointer++;
}
}
for (int i = 0; i < rootArrayDeriv.length; i++) {
double tempVal;
tempVal = poly(coefficients, rootArrayDeriv[i]);
tempVal = Math.abs(tempVal);
if (tempVal < threshold) {
rootArray[polyRootPointer] = rootArrayDeriv[i];
polyRootPointer++;
rootAns = true;
}
}
for (double i = leftEndPt; i < rightEndPt-resolution; i = i + resolution){
if (isPositive(coefficients, i) != isPositive(coefficients, i+resolution) || isPositive(coefficients, i) == 0) {
rootArray[polyRootPointer] = findRoot(coefficients, i, i+resolution, tolerance);
polyRootPointer++;
rootAns = true;
}
}
Arrays.sort(rootArray);
if (rootAns == false) {
System.out.println("Sorry - no roots were found at that particular interval.");
}
}
} else {
for (int i = 0; i < rootArray.length; i++) {
if (rootArray[i] != 0.0) {
System.out.printf("Root found at %.5f%n", Arrays.sort(rootArray));
}
}
static double poly(double[] C, double x){
double polySum = 0;
coArrayC[0] = C[0];
for (int i = 1; i < coArrayC.length; i++){
coArrayC[i] = C[i]*(Math.pow(x, i));
}
for (int i = 0; i < coArrayC.length; i++){
polySum = polySum + coArrayC[i];
}
return(polySum);
}
static double[] diff(double[] C){
for (int i = 0; i < degree; i++){
coArrayD[i] = (i+1)*C[i+1];
}
return(coArrayD);
}
static double findRoot(double[] C, double a, double b, double tolerance){
double root = 0.0 , residual;
while ( Math.abs(b - a) > tolerance ) {
root = (a + b) / 2.0;
residual = poly(C, root);
if (poly(C, a) > 0 && poly(C, b) < 0) {
if (residual > 0)
a = root;
else
b = root;
} else if (poly(C, a) < 0 && poly(C, b) > 0) {
if (residual > 0)
b = root;
else
a = root;
}
}
return(root);
}
static int isPositive(double[] C, double a){
double endpointTempA;
endpointTempA = poly(C, a);
if (endpointTempA < 0) {
return(1);
} else if (endpointTempA > 0) {
return(2);
} else {
return(0);
}
}
}
Let's say that I want to calculate the square root of 8. There are two ways to display the result as you can see here:
I think that the best way I have to obtain the second solution is this:
I want to try do display in my Java application 2√2 instead of 2,828427... and so I thought to develop a class following these steps. Let's consider the square root of 8.
Get the prime factors of 8 (2*2*2)
Count the exponent and try to export them (2^2 * 2 --> 2√2)
I have developed, as you can see below, a code that outputs the factors. If you input 8, the method estraiRadice() will output 2 * 2 * 2, which is correct.
private int b = 2;
public String estraiRadice(double x) {
String resRad = "";
int[] exponents = new int[100];
//Scomposizione in fattori primi
while (x > 1) {
if ((x % b) == 0) {
x /= b;
resRad += String.valueOf(b) + " * ";
} else {
b++;
}
}
return resRad;
}
The second step is giving me problems because I don't know exactly how to do create the power of a number and export it from the square root. I mean: how can that √2*2*2 become a √4*2 and then 2√2?
I thought that I could store in an array the exponent for each base and then try to export it somehow. Do you have any advice?
Try this:
public static int[] squareRoot(int number) {
int number1 = number;
List<Integer> roots = new ArrayList<>();
int coefficient = 1;
for (int i = 2; i < number1; i++) {
if (number1 % (i * i) == 0) {
roots.add(i);
number1 /= i * i;
for (int j = 2; j < number1; j++) {
if (number1 % (j * j) == 0) {
roots.add(j);
number1 /= j * j;
}
}
}
}
for (int root : roots) coefficient *= root;
return new int[]{coefficient, number1};
}
You can call it like this:
System.out.println(squareRoot(96)[0] + "√" + squareRoot(96)[1]);
You can use a HashMap to store prime number power pairs
HashMap<Integer,Integer> getRoots(int x)
{
HashMap<Integer,Integer> retval = new HashMap<Integer,Integer>();
int i=2;
while(i<=x)
{
int power = 0;
while( x%i == 0)
{
power++;
x /= i;
}
if(power>0)
{
retval.put(i,power);
}
if(x==1)
{
break;
}
i++;
}
return retval;
}
This is my program
// ************************************************************
// PowersOf2.java
//
// Print out as many powers of 2 as the user requests
//
// ************************************************************
import java.util.Scanner;
public class PowersOf2 {
public static void main(String[] args)
{
int numPowersOf2; //How many powers of 2 to compute
int nextPowerOf2 = 1; //Current power of 2
int exponent= 1;
double x;
//Exponent for current power of 2 -- this
//also serves as a counter for the loop Scanner
Scanner scan = new Scanner(System.in);
System.out.println("How many powers of 2 would you like printed?");
numPowersOf2 = scan.nextInt();
System.out.println ("There will be " + numPowersOf2 + " powers of 2 printed");
//initialize exponent -- the first thing printed is 2 to the what?
while( exponent <= numPowersOf2)
{
double x1 = Math.pow(2, exponent);
System.out.println("2^" + exponent + " = " + x1);
exponent++;
}
//print out current power of 2
//find next power of 2 -- how do you get this from the last one?
//increment exponent
}
}
The thing is that I am not allowed to use the math.pow method, I need to find another way to get the correct answer in the while loop.
Powers of 2 can simply be computed by Bit Shift Operators
int exponent = ...
int powerOf2 = 1 << exponent;
Even for the more general form, you should not compute an exponent by "multiplying n times". Instead, you could do Exponentiation by squaring
Here is a post that allows both negative/positive power calculations.
https://stackoverflow.com/a/23003962/3538289
Function to handle +/- exponents with O(log(n)) complexity.
double power(double x, int n){
if(n==0)
return 1;
if(n<0){
x = 1.0/x;
n = -n;
}
double ret = power(x,n/2);
ret = ret * ret;
if(n%2!=0)
ret = ret * x;
return ret;
}
You could implement your own power function.
The complexity of the power function depends on your requirements and constraints.
For example, you may constraint exponents to be only positive integer.
Here's an example of power function:
public static double power(double base, int exponent) {
double ans = 1;
if (exponent != 0) {
int absExponent = exponent > 0 ? exponent : (-1) * exponent;
for (int i = 1; i <= absExponent; i++) {
ans *= base;
}
if (exponent < 0) {
// For negative exponent, must invert
ans = 1.0 / ans;
}
} else {
// exponent is 0
ans = 1;
}
return ans;
}
If there are no performance constraints you can do:
double x1=1;
for(int i=1;i<=numPowersOf2;i++){
x1 =* 2
}
You can try to do this based on this explanation:
public double myPow(double x, int n) {
if(n < 0) {
if(n == Integer.MIN_VALUE) {
n = (n+1)*(-1);
return 1.0/(myPow(x*x, n));
}
n = n*(-1);
return (double)1.0/myPow(x, n);
}
double y = 1;
while(n > 0) {
if(n%2 == 0) {
x = x*x;
}
else {
y = y*x;
x = x*x;
}
n = n/2;
}
return y;
}
It's unclear whether your comment about using a loop is a desire or a requirement. If it's just a desire there is a math identity you can use that doesn't rely on Math.Pow.
xy = ey∙ln(x)
In Java this would look like
public static double myPow(double x, double y){
return Math.exp(y*Math.log(x));
}
If you really need a loop, you can use something like the following
public static double myPow(double b, int e) {
if (e < 0) {
b = 1 / b;
e = -e;
}
double pow = 1.0;
double intermediate = b;
boolean fin = false;
while (e != 0) {
if (e % 2 == 0) {
intermediate *= intermediate;
fin = true;
} else {
pow *= intermediate;
intermediate = b;
fin = false;
}
e >>= 1;
}
return pow * (fin ? intermediate : 1.0);
}
// Set the variables
int numPowersOf2; //How many powers of 2 to compute
int nextPowerOf2 = 1; //Current power of 2
int exponent = 0;
/* User input here */
// Loop and print results
do
{
System.out.println ("2^" + exponent + " = " + nextPowerOf2);
nextPowerOf2 = nextPowerOf2*2;
exponent ++;
}
while (exponent < numPowersOf2);
here is how I managed without using "myPow(x,n)", but by making use of "while". (I've only been learning Java for 2 weeks so excuse, if the code is a bit lumpy :)
String base ="";
String exp ="";
BufferedReader value = new BufferedReader (new InputStreamReader(System.in));
try {System.out.print("enter the base number: ");
base = value.readLine();
System.out.print("enter the exponent: ");
exp = value.readLine(); }
catch(IOException e){System.out.print("error");}
int x = Integer.valueOf(base);
int n = Integer.valueOf(exp);
int y=x;
int m=1;
while(m<n+1) {
System.out.println(x+"^"+m+"= "+y);
y=y*x;
m++;
}
To implement pow function without using built-in Math.pow(), we can use the below recursive way to implement it. To optimize the runtime, we can store the result of power(a, b/2) and reuse it depending on the number of times is even or odd.
static float power(float a, int b)
{
float temp;
if( b == 0)
return 1;
temp = power(a, b/2);
// if even times
if (b%2 == 0)
return temp*temp;
else // if odd times
{
if(b > 0)
return a * temp * temp;
else // if negetive i.e. 3 ^ (-2)
return (temp * temp) / a;
}
}
I know this answer is very late, but there's a very simple solution you can use if you are allowed to have variables that store the base and the exponent.
public class trythis {
public static void main(String[] args) {
int b = 2;
int p = 5;
int r = 1;
for (int i = 1; i <= p; i++) {
r *= b;
}
System.out.println(r);
}
}
This will work with positive and negative bases, but not with negative powers.
To get the exponential value without using Math.pow() you can use a loop:
As long as the count is less than b (your power), your loop will have an
additional "* a" to it. Mathematically, it is the same as having a Math.pow()
while (count <=b){
a= a* a;
}
Try this simple code:
public static int exponent(int base, int power) {
int answer = 1;
for(int i = 0; i < power; i++) {
answer *= base;
}
return answer;
}