java - Why is the output (Nan,Nan)? -
this question has answer here:
- what ^ operator in java? 16 answers
so i'm new java , have assignment class, i'm stuck. class supposed find intersection of 2 lines using quadratic equation. told have specific inputs class, d = 5, f = -3, g = 2, m = 1 , b = 3 , 2 intersections supposed (1,4) , (-.20,2.8). problem i'm running output returns (nan,nan) , (nan,nan) instead of right answer. there wrong code making me answer?
public class intersect{ public static void main(string args[]){ //prompt user parabola vars d f g system.out.println("enter constant d:"); int d = io.readint(); system.out.println("enter constant f:"); int f = io.readint(); system.out.println("enter constant g:"); int g = io.readint(); // y = dx^2 + fx + g //promt user line vars m b system.out.println("enter constant m:"); int m = io.readint(); system.out.println("enter 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 = d; int z = (f-m); int c = (g-b); double x1 = -z + (math.sqrt (z^2 - 4 * * c) / (2 * a)); double x2 = -z - (math.sqrt (z^2 - 4 * * c) / (2 * a)); double y1 = m * x1 + b; double y2 = m * x2 - b; //output each intersection on own line, system.out.println() ok answer submission system.out.println("the intersection(s) are:"); system.out.println("(" + x1 + "," + y1 + ")"); system.out.println("(" + x2 + "," + y2 + ")"); } }
^ xor operator in java , not exponentiation operator. therefore, expresson z ^ 2 - 4 * * c computes negative.
from input provide, z = -4, = 5, c = -1. expression translates -4 ^ 2 - 4 * 5 * -1. note * , + have higher precedence ^, i.e. order of evaluation (-4 ^ (2 - ((4 * 5) * -1))) = -22.
then you're trying find square root of -22, which, according math.sqrt(), nan.
use math.pow(z, 2), or use z * z instead:
math.sqrt(z * z - 4 * * c); // note: time operator precedence works, // should use parentheses wherever // expression seems ambiguous.
Comments
Post a Comment