How to resolve 'cannot find symbol' errors? - java

I am trying to solve a complicated mathematical expression using Java on Netbeans, however I have two problems: "cannot find symbol (variable)", and the result I get is always 'NaN'.
But when I tried 'double x = 0;' instead of 'double x;' my code works but the answer I get is always 'NaN'. I also tried initializing the variable on scan 'double x = scan.nextDouble();' but it doesn't work either.
Then I realized the pattern that most of the code I type that involves complicated math, needs to have '= 0;' for the variables to be found by the compiler.
So my real question is, what is the difference between 'double x = 0;' and 'double x;' Why does the former work in mathematical expressions, but the latter can't be detected by the compiler?
Unnecessary Information Below
//The code I made for my homework
double ans, num, den, x, y;
//double x = 0;
//double y = 0;
//variable x and y might not have been initialized
num = Math.cbrt( ((2 * Math.pow(x,4) * y) + (2 * x * Math.pow(y,4) )) );
den = (4 * x * Math.pow(y, ((2 * x) + (2 * y))));
ans = num / den;
System.out.print("x: ");
x = scan.nextDouble();
System.out.print("y: ");
y = scan.nextDouble();
System.out.println("\n The answer is " + ans);
I have the mathematical expression of ((\root(3)((2x^(4)y+2xy^(4)) )))/(4xy^(2x+2y))
I expect the output of
x: 2
y: 3
The answer is 0.096157...
Instead, I get the result of 'variable x and y might not have been initialized' and on another scenario I get the result of 'The answer is NaN'. I'm thinking if I can use variables for each term to solve it.
EDIT: I SUCCESSFULLY MADE THE DIVISION OF THE 'DOUBLES'
by removing the 'double x = 0;', I eliminated the possibility of
'NaN'. Instead, I declare and assign values to variables at the same time.
System.out.print("x: ");
double x = scan.nextDouble();
System.out.print("y: ");
double y = scan.nextDouble();
//preparation
//double term1, term2, term3, term4, term5, term6, exp; //x, y;
//double x = 0;
//double y = 0;
//variable x and y might not have been initialized
//double term1 = (Math.cbrt(2 * Math.pow(x,4) * y));
//double term2 = (Math.cbrt(2 * x * Math.pow(y,4)));
//double term3 = (4 * x);
//double term4 = (2 * x);
//double term5 = (2 * y);
// double exp = term4 + term5;
//double term6 = (Math.pow(y,exp));
//double num = (Math.cbrt((2 * Math.pow(x,4) * y) + (2 * x * Math.pow(y, 4))));
//double den = term3 * term6;
double num = (2 * Math.pow(x,4) * y) + (2 * x * Math.pow(y,4) );
double den = (4 * x * Math.pow(y, ((2 * x) + (2 * y))));
double ans = Math.cbrt(num / den);
System.out.println("\n The answer is " + ans);

Local variables must be given a value before they are referred to. Since your code executes from top to bottom, the calculations will be done before x and y are initialised to the user input values. This is why it says "variable might not be initialised" in your calculations.
Your misconception might be thinking that these lines define some kind of a "relationship" between x, y, num, den:
num = Math.cbrt( ((2 * Math.pow(x,4) * y) + (2 * x * Math.pow(y,4) )) );
den = (4 * x * Math.pow(y, ((2 * x) + (2 * y))));
ans = num / den;
But they actually don't. They simply do the calculations, and set the variable on the left hand side to the result. However, at this point, the values of x and y are not known yet, because the x = ... and y = ... lines haven't run yet.
What if you add double x = 0 and double y = 0 at the top? That solves the compiler error. The calculation can now be carried out, but it will use the x=0 and y=0. That's all the information it has got at that moment, as the lines where you get user input has not been run yet.
What you should do is to move the lines that read the user input before the calculations:
System.out.print("x: ");
x = scan.nextDouble();
System.out.print("y: ");
y = scan.nextDouble();
num = Math.cbrt( ((2 * Math.pow(x,4) * y) + (2 * x * Math.pow(y,4) )) );
den = (4 * x * Math.pow(y, ((2 * x) + (2 * y))));
ans = num / den;
System.out.println("\n The answer is " + ans);
Also, to get the expected output of 0.096157..., you need the cube root to apply to the whole fraction, not just the numerator:
num = (2 * Math.pow(x,4) * y) + (2 * x * Math.pow(y,4) );
den = (4 * x * Math.pow(y, ((2 * x) + (2 * y))));
ans = Math.cbrt(num / den);

So my real question is, what is the difference between double x = 0; and double x;
The former declares x and gives it an initial value.
The latter declares x and does not give it an initial value. You can give x a value later, but you must do this for all paths that lead to any use of the variable. For example:
double x;
if (Math.pow(2, 2) >= 0.0) {
x = 0.0;
} else {
x = 1.0;
}
System.out.println(x); // OK
versus
double x;
if (Math.pow(2, 2) >= 0.0) {
x = 0.0;
}
System.out.println(x); // ERROR
The latter is a compilation error because there is a possible path through the code where x may be used before it has been initialized.
Now anyone with highschool maths knowledge can tell you that the square of an integer will always be greater or equal to zero, and therefore the else branch will never be taken. However the Java compiler doesn't know this, and will give you a compilation error. (Indeed, it is not permitted to not give you a compilation error. I won't go into the details: they are in the JLS if you care.)
Why does the former work in mathematical expressions, but the latter can't be detected by the compiler?
Now that is an interesting question.
The answer is that = has a fundamentally different meaning in programming languages and mathematical equations.
In a programming language like Java, a = b; means "assign (set) the current value of a to the current value of b".
In an mathematical equation a = b means "for all places where these a and b variables are used, the value of a is equal to the value of b.". It is basically a constraint on the possible values of a and b.
Another way to think about this is that in mathematics, a variable in an equation represents a set of possible values. The equation constrains the set of values; e.g. a = sqrt(4) is equivalent to saying that a denotes {x | x * x == 4} which is the same as the set {-2, +2}.
Now mathematics does have cases where the notation is erroneous. For example a = a + 1 is equivalent to saying that a denotes {x | x == x + 1} ... which is the empty set.
(The notation I used above is not what classical mathematicians and formal methods people would normally use. Unfortunately, it is rather difficult to explain this unless you have taken some University level Mathematics subjects / units. Or a formal methods units in a Computer Science course.)
Finally, here are so generic Q&A's that address your other compilation and runtime errors:
What does a "Cannot find symbol" compilation error mean?
Variable might not have been initialized error
In Java, what does NaN mean?

Local variables including primitives do not have default values assigned and need to be initialized explicitly.
You have to set initial values for x and y, else the compiler protests.
Why must local variables, including primitives, always be initialized in Java?

Related

Why are my cos(x) outputs out of bound 1 and -1?

My task is to implement the cos(x) function withou using Math. library and with the taylor polynom, my code looks like this:
public class Cosinus {
public static void main(String[] args) {
/*if(args.length == 0){
System.out.println("ERROR: Geben Sie ein Argument für x ein!");
return;
}*/
double x = 5;
double summand1 = (x*x) / 2;
double summand2 = (x*x*x*x) / (2*3*4);
double summand3 = (x*x*x*x*x*x) / (2*3*4*5*6);
double summand4 = (x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8);
double summand5 = (x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10);
double summand6 = (x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12);
double summand7 = (x*x*x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12*13*14);
//double summand8 = (x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12*13*14*15*16);
//double summand9 = (x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12*13*14*15*16*17*18);
//double summand10 = (x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12*13*14*15*16*17*18*19*20);
double cosinusFunktion = (((((((1 - summand1) + summand2) - summand3) + summand4) - summand5) + summand6) - summand7);
System.out.println(cosinusFunktion);
}
}
For x = 1, 2, 3, and 4 Y is between 1 and -1
but with x = 5 it goes too -4 and if the x are even getting bigger this continues too 1287918274.
I cant solve this task but tthe task says it is enough to implement this funktion iwth the taylor polynom and the first 11 summand. I tried this too, but then even with x = 1 the bounds are broken. How can i solve this, so x = 42.5 is in bound of -1 and 1?
Tried more summands to make the result more excact, but the bounds get broken even more.
tried implement the periodicity of x-2*PI, but I dont know where to put it and results get messed up eeven more.
you are getting an integer overflow for the factorial in the summand7 line
as a simple fix you can change the line to:
double summand7 = (x*x*x*x*x*x*x*x*x*x*x*x*x*x) / ((double) 2*3*4*5*6*7*8*9*10*11*12*13*14);
The Taylor expansion will always blow up for larger inputs. However, since:
sin(x) = sin(x + n*2*pi) // for any integer n
You can simply pre-process you input with a modulus function to prevent your output from blowing up.
I can't test compile right now, but if memory serves, you would add one of the following lines prior to computing your first summand:
x = x%(Math.PI*2)
Or, if you can't use Math
x = x%((double)3.14159265358979323846*2)

Arithmetic problems with java longs

I have two equations: x * x - D * y * y = 1 and x = sqrt(1 + D * y * y).
Both are algebraic manipulations of the other.
Given D, I need to solve for the smallest integer value of x so that y is also an integer. I loop through possible y values, plug them into the second equation and test if x is an integer. If it is, I return x.
The problem I have is when x, y, and D are plugged into the 1st equation, it does not equal 1.
These are some problematic values:
1. x=335159612 y=42912791 D=61
2. x=372326272 y=35662389 D=109
My intuition is that java's Math.sqrt method does not calculate such a small decimal, however BigDecimal does not have a square root method.
Is my math just wrong? If not, what can I do to accurately calculate x and y?
Edit: Here is the root of the problem along with the method that tests if a double is a a natural number.
public static void main(String[] args){
long x = 335159612, D = 61, y = 42912791;
System.out.println(Math.sqrt(D * y * y + 2)); // 3.35159612E8
System.out.println(x * x - D * y * y); // 3
}
public static boolean isNatural(double d){
return d == (int)d;
}
Be careful with precisions in 'double'.
As per IEEE 754-1985 the double precision provides 16 digits (15,9 to be absolutely precise).
E.g.
a) SQRT(112331965515990542) is
335159611.99999999701634694576505237017910
Which, when converted into double, gives 3.3515961199999999E8
b) SQRT(112331965515990543)
335159611.99999999850817347288252618840968
Which, when converted into double, gives 3.3515961199999999E8.
So, as per IEEE 754-1985 definition, those values are equal.
Apparently, any further logical/mathematical checks will be, generally speaking, inaccurate.
To overcome this limitation I recommend BigMath package from www.javasoft.ch
import ch.javasoft.math.BigMath;
import java.math.BigDecimal;
class Tester {
public static void main(String[] args) {
long D = 61L, y = 42912791L;
double a = Math.sqrt(D * y * y + 1);
double b = Math.sqrt(D * y * y + 2);
System.out.println(a);
System.out.println(b);
System.out.println(a == b);
BigDecimal bda = BigMath.sqrt(new BigDecimal(D * y * y + 1), 32);
BigDecimal bdb = BigMath.sqrt(new BigDecimal(D * y * y + 2), 32);
System.out.println(bda.toString());
System.out.println(bdb.toString());
System.out.println(bda.equals(bdb));
}
}
Result:
3.35159612E8
3.35159612E8
true
335159611.99999999701634694576505237017910
335159611.99999999850817347288252618840968
false
P.s. to completely ruin your faith in standard Java maths try this:
System.out.println(0.9200000000000002);
System.out.println(0.9200000000000001);
You will see:
0.9200000000000002
0.9200000000000002
This kind of Diophantine's equations is known as Pell's equations.
Wiki.
Mathworld.
Both links contain clues - how to solve this equation using continued fractions.
I think it would be nice to apply some math instead of brutforce/
If sqrt is the issue, use the first equation instead. If x is an integer, x^2 will also be an integer; if x is not an integer, then x^2 would also not be an integer, as long as you are using BigDecimals with sufficient scale for your math and not doubles.

Why is the output (Nan,Nan)? [duplicate]

This question already has answers here:
What does the ^ operator do in Java?
(19 answers)
Closed 7 years ago.
So I'm new to Java and I have an assignment to do for class, but I'm stuck. The class is supposed to find the intersection of two lines using the quadratic equation. I was told to have specific inputs for class, so d = 5, f = -3, g = 2, m = 1 and b = 3 and the two intersections are supposed to be (1,4) and (-.20,2.8). The problem I'm running into is that the output returns (NaN,NaN) and (NaN,NaN) instead of the right answer. Is there anything wrong with my code that is making me get this answer?
public class Intersect{
public static void main(String args[]){
//prompt user for parabola vars d f g
System.out.println("Enter the constant d:");
int d = IO.readInt();
System.out.println("Enter the constant f:");
int f = IO.readInt();
System.out.println("Enter the constant g:");
int g = IO.readInt();
// y = dx^2 + fx + g
//promt user for line vars m b
System.out.println("Enter the constant m:");
int m = IO.readInt();
System.out.println("Enter the constant b:");
int b = IO.readInt();
// y = mx + b
//compute intersection
// dx^2 + fx + g = mx + b
// x^2 * (d) + x * (f-m) + (g-b) = 0
int a = d;
int z = (f-m);
int c = (g-b);
double x1 = -z + (Math.sqrt (z^2 - 4 * a * c) / (2 * a));
double x2 = -z - (Math.sqrt (z^2 - 4 * a * c) / (2 * a));
double y1 = m * x1 + b;
double y2 = m * x2 - b;
//output each intersection on its own line, System.out.println() is ok for this answer submission
System.out.println("The intersection(s) are:");
System.out.println("(" + x1 + "," + y1 + ")");
System.out.println("(" + x2 + "," + y2 + ")");
}
}
^ is the xor operator in java and not the exponentiation operator. Therefore, the expresson z ^ 2 - 4 * a * c computes to something negative.
From the input you provide, z = -4, a = 5, c = -1. The expression translates to -4 ^ 2 - 4 * 5 * -1. Note that * and + have a higher precedence than ^, i.e. the order of evaluation is (-4 ^ (2 - ((4 * 5) * -1))) = -22.
Then you're trying to find the square root of -22, which, according to Math.sqrt(), is NaN.
Use Math.pow(z, 2), or simply use z * z instead:
Math.sqrt(z * z - 4 * a * c); // Note: This time operator precedence works,
// But you should use parentheses wherever
// the expression seems ambiguous.
First of all ^ is not an exponentiation operator, what causes Nan is the fact that you pass in a negative argument to Math.sqrt.
From java reference ( http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html ):
public static double sqrt(double a)
Returns the correctly rounded positive square root of a double value. Special cases:
If the argument is NaN or less than zero, then the result is NaN.
If the argument is positive infinity, then the result is positive infinity.
If the argument is positive zero or negative zero, then the result is the same as the argument.
Otherwise, the result is the double value closest to the true mathematical square root of the argument value.
Parameters:
a - a value.
Returns:
the positive square root of a. If the argument is NaN or less than zero, the result is NaN.
Its your order of operations that is causing you to get NaN results.
Try this(added variables for convenience):
int a = d;
int z = f - m;
int negZ = -z;
int c = g - b;
double sq = Math.sqrt((z * z) - (4 * a * c));
double a2 = 2 * a;
double x1 = (negZ + sq) / a2;
double x2 = (negZ - sq) / a2;
double y1 = (m * x1) + b;
double y2 = (m * x2) - b;

Need Help Finding the intersection of two equations in Java

I saw someone else posted this problem but didn't word it properly so he didn't end up receiving any help, so I figured I would try and be more direct.
Here is the problem proposed to us :
// Write and submit your code in a file called Intersect.java. Use the IO module to read inputs. Use System.out.println() to print your answer.
Write a program that calculates the intersection between 2 equations:
a degree-2 (quadratic) polynomial i.e.
y = dx^2 + fx + g
where d, f, and g are constants
and a degree-1 (linear) equation i.e.
y = mx + b
where m is the slope and b is a constant
The above is just text, not code that could appear in a Java program.
Ask the user for the constant values in each equation. Output the intersection(s) as ordered pair(s) (x,y), or "none" if none exists. Below is an example run.
java Intersect
Enter the constant d:
5
Enter the constant f:
-3
Enter the constant g:
2
Enter the constant m:
1
Enter the constant b:
3
The intersection(s) is/are:
(1,4)
(-0.20,2.8)
//
The main problem is essentially asking us to write a code that asks the user to imput the individual constants and the slope of the two equations, one being a quadratic polynomial and the other being a linear equation in point-slope.
I understand that we have to use the quadratic equation in the code, however I have no idea how to actually code this in.
Once we have had the user imput the constants, in this case 5 (d,f,g,m,b; with m being slope) we need to have the code run the calculations to imput those constants into the above example ( y = dx^2 + fx + g | y = mx + b) and return either "none" if there is no intersection, or if it does intersect, the ordered pair at which it does intersect (x,y).
I know already that if 0 is entered as the constants it returns (NaN,NaN) which I also know needs to be re-written to None.
so far I only have the following:
public class Intersect {
public static void main(String[] args) {
System.out.println("Enter the constant d:");
int d = IO.readInt();
System.out.println("Enter the constant f:");
int f = IO.readInt();
System.out.println("Enter the constant g:");
int g = IO.readInt();
System.out.println("Enter the constant m:");
int m = IO.readInt();
System.out.println("Enter the constant b:");
int b = IO.readInt();
If anyone can shed some light on this that would be fantastic, thanks!
EDIT1 :
So far i've changed the code to the following, however, I still don't know how to get it to return to me an answer:
public class Intersect {
public static void main(String[] args) {
System.out.println("Enter the constant d:");
int d = IO.readInt();
System.out.println("Enter the constant f:");
int f = IO.readInt();
System.out.println("Enter the constant g:");
int g = IO.readInt();
System.out.println("Enter the constant m:");
int m = IO.readInt();
System.out.println("Enter the constant b:");
int b = IO.readInt();
//y = dx^2 + fx + g
//y = mx + b
//mx + b = dx^2 + fx + g
//x^2 * (d) + x * ( f - m ) + ( g - b )
int A = d;
int B = f - m;
int C = g - b;
double x1 = - B + Math.sqrt( B^2 - 4 * A * C ) / (2 * A);
double x2 = - B - Math.sqrt( B^2 - 4 * A * C ) / (2 * A);
double y1 = m * x1 + b;
double y2 = m * x1 + b;
}
Also, eclipse is telling me that x2,y1, and y2 aren't used at all.
I know I need to use System.out.println() however I don't understand what I can put there to make the answer an ordered pair. Also, I tried setting an If statement to have the answer return None instead of NaN however it instead returns, NaN None.
There are a lot of special cases you have to take into account.
I hope I've got them all right.
So after the initialization of the values you can put this:
// calculating some useful values.
double t = -(f - m) / (2.0 * d);
double u = t * t - (g - b) / (double) d;
// the first polynomial is linear, so both terms are.
if (d == 0) {
// both linear functions have the same slope.
if (f == m) {
// both functions are shifted the same amount along the y-Axis.
if (g == b)
// the functions lie on top of each other.
System.out.println("There is an infinite amount intersections");
// the functions are shifted different amounts along the y-Axis.
else
// the lines are parallel.
System.out.println("There are no intersections");
}
// both linear functions have different slopes.
else {
// solve linear equation.
double x = (b - g) / (double) (f - m);
double y = m * x + b;
System.out.println("The intersection is: (" + x + "," + y + ")");
}
}
// the functions do not cross each other.
else if (u < 0)
System.out.println("There are no intersections");
// the linear function is a tangent to the quadratic function.
else if (u == 0) {
// solve equation.
double x = t;
double y = m * x + b;
System.out.println("The intersection is: (" + x + "," + y + ")");
}
// the linear function intersects the quadratic function at two points.
else {
// solve quadratic equation.
double x1 = t + Math.sqrt(u);
double x2 = t - Math.sqrt(u);
double y1 = m * x1 + b;
double y2 = m * x2 + b;
System.out.println("The intersections are: (" + x1 + "," + y1 + ") (" + x2 + "," + y2 + ")");
}
i guess....
//y = dx^2 + fx + g
//y = mx + b
//mx + b = dx^2 + fx + g
//x^2 * (d) + x * ( f - m ) + ( g - b )
A = d
B = f - m
C = g - b
x1 = - B + sqr( B^2 - 4 * A * C ) / (2 * A)
x2 = - B - sqr( B^2 - 4 * A * C ) / (2 * A)
y1 = m * x1 + b
y2 = m * x1 + b

java code to compute some multiple of a number?

I am using Math.PI in my example, so it is a double. It is a simple code but there is a bit I am not sure how to do:
I want the code to calculate the fundamental period X of a sin or cos function with a multiplier value a given by the user. The n value is initialized at n=1 and is an integer value.
If the result of (2 * pi * n)/a = X is lower than pi then n should increment, and it should keep going until that number is a multiple of pi, then print the result.
Just to clarify: a is a multiplier of x which goes in the function sin or cos like this:
cos(ax)
sin(ax)
The bit I am having the trouble with is working out whether the number is a multiple of pi (provided it's already greater than pi, that is).
This is about as far as I got and it's incomplete.
public void printSinusoidalPeriod(double multiplier /* this would be `a` */){
double pi=Math.PI;
double p = (2 * pi * (double) n) / multiplier;
while(p<pi){
if(n%pi==0){
n=n+1;
System.out.println(n);
p = (2 * pi * (double) n) / multiplier;
}
}
p= (double)Math.round(p * 100) / 100;
System.out.println("period of function is = " + p + " and n = " + n);
}
It seems like it's not going into the if statement and getting caught in the while loop
If I understand your problem correctly, I had to solve a similar problem to this before using php. Not sure what the correct syntax is for javascript but maybe you should keep a counter that continues until (x/pi) is an integer which would indicate it is a multiple of pi..
I know this isn't the correct code but something like:
while (!isint(x/pi)) {
x++;
}
if (isint(x/pi)) {
//CODE TO EXECUTE
}
If I understand you correctly
while((2 * pi * n)/a)<pi)
{
if(!(n%pi==0))
{
n++;
}
}
multiple of y is the part you need to figure out yourself. but this should help you with the logic, If I have understood u correctly.
You appear to be calculating when
(2 * pi * n)/a = m * pi where m is some integer multiple.
so
2 * pi * n = m * pi * a
2 * n = m * a
n = m * a / 2
You other constraint is
(2 * pi * n)/a < pi
so
2 * pi * n < pi * a
2 * n < a
n < a / 2;
For both equations to be true, m must be an integer less than 1, but since you are starting at 1 for n it will never be true.
Ok here's how I did it in the end, with the help of the suggestions here.
public void printSinusoidalPeriod(double a){
double pi=Math.PI;
double p=m*pi;
while(n<a/2){
if((double)Math.round((n*pi)%pi)!=0.01){
n=n+1;
m = (int) Math.round(((2 * (double) n) / a));
p= (double)Math.round(m * pi * 100) / 100;
p=p*n;
}
}
System.out.println("period of function is = " + p + " and n = " + n);
System.out.println("Check: p/n = " + p/n);
}
Please let me know if you can spot any problems with the logic. I have not gone through many possibities yet, but the ones I did, looked okay to me.

Categories

Resources