I'm not sure how to write an equation in Netbeans.
The equation is supposed to be: (5−x)^2 +(5−y)^2 all under a square root.
This is what I have tried:
public static int getScore(int x, int y){
return ( (((5-x)^2 + (5-y)^2))^(1/2) );
This is one of those cases where there's a specialized library function:
return Math.hypot(5-x, 5-y);
This avoids the overflow and underflow issues in computing the square root of the sum of squares directly
The carat ^ performs exclusive or operator in java, which is a bits thing. Don't use it for exponents.
The expression you are looking for is
return Math.sqrt(Math.pow(5 - x, 2) + Math.pow(5 - y, 2)));
Related
Here is an assignment:
"Let's say you are given a number, a, and you want to find its
square root. One way to do that is to start with a very rough guess about
the answer, x0, and then improve the guess using the following formula
x1 = (x0 + a/x0)/2
For example, if we want to find the square root of 9, and we start with x0 = 6,
then x1 = (6 + 9/6)/2 = 15/4 = 3.75, which is closer.
We can repeat the procedure, using x1 to calculate x2, and so on. In this
case, x2 = 3.075 and x3 = 3.00091. So that is converging very quickly on the
right answer(which is 3).
Write a method called squareRoot that takes a double as a parameter and
that returns an approximation of the square root of the parameter, using this
technique. You may not use Math.sqrt.
As your initial guess, you should use a/2. Your method should iterate until
it gets two consecutive estimates that differ by less than 0.0001; in other
words, until the absolute value is less than 0.0001. You can use
Math.abs to calculate the absolute value."
This is exercise meant to practice while loop. As you see I did the assignment, I think it works ? But I am not sure how did I come to solution ? In other words, what should I improve here ? Is there any other way to enter the loop differently ? How to name variables more appropriately ? And lastly, is my approach good or bad here ?
public class squareRoot {
public static void main(String args[]){
System.out.println(squareRoot(192.0));
}
public static double squareRoot(double a){
double gs = a/2; //guess
double ig = (gs + (a/gs))/2; //improving guess
double ig1 = (ig + (a/ig))/2; //one more improving guess, ig1
while (Math.abs((ig-ig1)) > 0.0001){ //with ig and ig1, I am entering the loop
ig = (ig1 + (a/ig1))/2;
ig1 = (ig + (a/ig))/2; //ig1 has to be less then ig
}
return ig1;
}
}
Your approach is nearly correct.
Let's talk about variables first. IMO, you should use full names for variables instead of acronyms. Use guess instead of gs. Use improvedGuess instead of ig etc.
Now that's out of the way we can see where your problem lies. For the while loop to finish, two consecutive guesses' difference must be less than 0.0001. However, here you are only comparing the 1st and 2nd guesses, the 3rd and 4th guesses, the 5th and 6th guesses etc. What if the 4th and 5th guesses' difference is less than 0.0001? Your loop won't stop. Instead, it returns the value of the 6th guess. Although it is more accurate, it does not fulfill the requirement.
Here's what I've come up with
public static double squareRoot(double a){
double guess = a/2;
double improvedGuess = (guess + (a/guess))/2;
while (Math.abs((guess - improvedGuess)) > 0.0001){
guess = improvedGuess;
improvedGuess = (guess + (a/guess))/2;
}
return improvedGuess;
}
Here is my Solution
private static double squareRoot(double a){
double x0= a/2;
while (true) {
double x1 = (x0 + a / x0) / 2;
if (Math.abs(x1 - x0) < 0.0001) {
break;
}
x0=x1;
}
return x0;
}
I'm trying to make a program that outputs the roots of a given cubic equation. I therefore decided to make a version using the cubic formula (http://www.math.vanderbilt.edu/~schectex/courses/cubic/). This formula should be able to output the result of one of the roots.
However, it doesnt seem to work and I'm not sure if it the code or the idea that is flawed. Here the coefficients 1, -6, 11 and -6 should create an output of either 1, 2 or 3. Instead NaN is outputted. The same has applied to other coefficients I have tried to use. Thanks for all your help!
public class CubicFormula {
public static void main(String[] args) {
System.out.println(new CubicFormula().findRoots(1.0, -6.0, 11.0, -6.0));
}
public double findRoots(double a, double b, double c, double d) {
double p = -(b)/(3*a);
double q = Math.pow(p, 3) + (b*c - 3*a*d)/(6*Math.pow(a, 2));
double r = c/(3*a);
return Math.cbrt(q + Math.sqrt(Math.pow(q, 2.0) + Math.pow((r - Math.pow(p, 2.0)), 3)))
+ Math.cbrt(q - Math.sqrt(Math.pow(q, 2.0) + Math.pow((r - Math.pow(p, 2.0)), 3))) + p;
}
}
From the very link you have mentioned
One reason is that we're trying to avoid teaching them about complex numbers. Complex numbers (i.e., treating points on the plane as numbers) are a more advanced topic, best left for a more advanced course. But then the only numbers we're allowed to use in calculus are real numbers (i.e., the points on the line). That imposes some restrictions on us --- for instance, we can't take the square root of a negative number. Now, Cardan's formula has the drawback that it may bring such square roots into play in intermediate steps of computation, even when those numbers do not appear in the problem or its answer.
This part
Math.sqrt(Math.pow(q, 2.0) + Math.pow((r - Math.pow(p, 2.0)), 3))
will end up being sqrt of negative number, which is imaginary, but in java
doubles world ends up being NaN.
How does one figure out how many times one has to add a short to get the value of another short?
I know, I know, it's a weirdly phrased question. But in more specifics without all the primitive types of Java...
Basically, I have a short x, which we'll use the placeholder 7 for. I also have a short y, which I'll say is the number 5. And then, I have a short z, which I'll say is 236.
Now, what I want to do, is get an integer that counts how many times I have to add the number y (5) to the number x (7) to get to the maximum value of z (236).
Obviously, I could do that somewhat with a pencil and paper right now, but what I need is something that I can input the 3 values and it will give me the integer as the output - the number of times I have to add the value y to the number x to get to the maximum value of z.
If you still don't understand what I'm doing, then a more visual example is:
(Y * someint) + X = Z How would I get to someint?
int result = (z - x) / y;
The result is int even if division has a remainder which is ignored in this case.
As others have stated this is simple division. But if you're looking for other completely unnecessary ways to do this, heres a loop way...
public static int getNumOfAdds(short x, short y, short target){
int i;
for(i = 0; y*i + x < target; i++){}
return i;
}
val = (Z-X)/Y;
rem_val = (Z-X)%Y;
if (rem_val != 0)
val++;
This should do it.
Recursively?
Try something like
Func(short x , short y, short z, int c)
if ( x >= z )
return c
else
return Func(x+y,y,z,c)
and your first call would be Func(x,y,z,0)
I've been having problems with my code for two weeks, and have been unsuccessful in debugging it. I've come here in the hope that someone can help. I've written a program that utilizes the Barnes-Hut algorithm for n-body gravitational simulation. My problem is that one or more 'particles' will have the position of {NaN, NaN, NaN} assigned to them (using three doubles to represent x, y, z of 3-d space). This, in turn, causes the other particles to have an acceleration of {NaN, NaN, NaN}, and in turn, a velocity and position of {NaN, NaN, NaN} as well. Basically, after a frame or two, everything disappears. It seems to be occurring in the updateAcc method, but I have a feeling that this isn't so. I understand that this is a huge undertaking, and am very grateful for anyone that helps me.
What I've checked:
There are no negative square roots, and all the values seem to be within their limits.
The source code is available here. Thanks again.
Code that seems to produce NaN:
private static void getAcc(particle particle, node node)
{
if ((node.particle == null && node.children == null) || node.particle == particle)
{
//Geting gravity to a node that is either empty or the same node...
}
else if (distance(node.centerOfMass, particle.position) / node.sideLength > theta && node.children != null)
{
for (int i = 0; i < node.children.length; i++)
{
if (node.children[i] != null)
{
getAcc(particle, node.children[i]);
}
}
}
else
{
particle.acceleration = vecAdd(particle.acceleration, vecDiv(getForce(particle.position, particle.mass, node.centerOfMass, node.containedMass), particle.mass));
}
}
private static double sumDeltaSquare(double[] pos1, double[] pos2)
{
return Math.pow(pos1[0]-pos2[0],2)+Math.pow(pos1[1]-pos2[1],2)+Math.pow(pos1[2]-pos2[2],2);
}
private static double[] getForce(double[] pos1, double m1, double[] pos2, double m2)
{
double ratio = G*m1*m2;
ratio /= sumDeltaSquare(pos1, pos2);
ratio /= Math.sqrt(sumDeltaSquare(pos1,pos2));
return vecMul(vecSub(pos2, pos1), ratio);
}
private static double distance(double[] position, double[] center)
{
double distance = Math.sqrt(Math.pow(position[0]-center[0],2) + Math.pow(position[1]-center[1],2) + Math.pow(position[2]-center[2],2));
return distance;
}
I'm not sure if this is the only problem, but it is a start.
sumDeltaSquare will sometimes return 0 which means when the value is used in getForce ratio /= sumDeltaSquare(pos1, pos2); it will produce Infinity and start causing issues.
This is a serious problem that you need to debug and work out what everything means. I enjoyed looking at the dots though.
Firstly, why aren't you using Java's Vecmath library? (It's distributed as a part of Java3D. Download Java3D's binary build and then just use vecmath.jar) Your problem is, very likely, somewhere in your custom vector functions. If not, #pimaster is probably right in that your translation magnitude method sumDeltaSquare might be returning 0 if two of your masses occupy a single space. Which means, unless you're inside a black hole, you're doing it wrong :P. Or you need to come up with a quantum gravity theory before you can do this simulation.
If you can't use vecmath (i.e. this is a homework assignment) I would suggest you use a regex to find every instance of return * and then replace it with assert !Double.isNan(*) && Double.isFinite(*);\nreturn *, except substitute * for whatever regex finds a "match group". I've forgotten exactly what that is, but I got you started on Google. I also suggest you avoid optimizations until after you have working code.
I'm not going to debug your code. But NaN values are the result of mathematically invalid operations on floating point numbers. The most famous of those is division by 0 (does not throw an exception with floating point).
How can this happen?
If your computation produces very small numbers, they might become too small to be represented as 64-bit floating point numbers (they require more bits than are available), and Java will return 0.0 instead.
In the other direction, if you get an overflow (the magnitude of the number requires too many bits), Java turns this into infinity. Doing math with infinity and 0 can quickly lead to NaN, and NaN propagates through every operation you apply to it.
For details, see sections 4.2 and 15.17 of the Java language spec.
import java.lang.Math;
import java.awt.*
public class Triangle implements Shape
{
java.awt.Point a;
java.awt.Point b;
java.awt.Point c;
public Triangle(java.awt.Point a, java.awt.Point b, java.awt.Point c)
{
this.a = a;
this.b = b;
this.c = c;
}
public double getArea( )
{
double area;
return area = Math.abs((a-c)*(b-a)-(a-b)*(c-a));
} ...
http://upload.wikimedia.org/math/f/e/5/fe56529cdaaaa9bb2f71c1ad8a1a454f.png <--area formula
I am trying to calculate the area of a triangle from 3 points (x,y) from a 2D Cartesian coordinate system. I'm assuming that my above formula correctly yields the area of a triangle (if not, please correct me) but my compiler says "operator - cannot be applied to java.awt.Point,java.awt.Point". I'm assuming it's saying this because you cannot subtract points from each other, but each value in the formula is either an x or y value, not a point. How can I fix my code so this would work?
Thanks!
According to Wikipedia, you formula is correct. The article contains lots of useful and clear data.
According to the java.awt.point documentation, you should use the getX() and getY() methods, which return the coordinate value of a point.
That is,
Should be expressed as:
Math.abs((a.getX()-c.getX())*(b.getY()-a.getY())-
(a.getX()-b.getX())*(c.getY()-a.getY()))*0.5;
It is probably not such a good practice to use point.x, because you shouldn't access an object's variable if you have a getter method that does that. This is the one aspect of separation between interface and implementation: the data point.x might be stored in many forms, not just int; The interface method assures that you'll get an int every time you use it.
compiler is telling you the exact right thing.
Math.abs((a-c)*(b-a)-(a-b)*(c-a)
you forgot .x in a.x .y in b.y etc. that is (a.x - c.x)* ...
Update: I didn't notice that OP had linked to a formula, that's why I looked up this one and coded it. You should use the other formula as this one involves more calculations (including 4 calls to sqrt, I think that would be heavy).
Using Heron's formula
double distance(Point a, Point b)
{
double dx = a.x - b.x;
double dy = a.y - b.y;
return Math.sqrt(dx * dx + dy * dy);
}
double getArea()
{
double ab = distance(a, b);
double bc = distance(c, b);
double ca = distance(a, c);
double s = (ab + bc + ca) / 2;
return Math.sqrt(s * (s - ab) * (s - bc) * (s - ca))
}
As the linked formula says, don't calculate with the points but with their x- and y-values. I'll leave it to you (it's homework!) to do that in java.
And don't forget to divide by 2.
Use a.x - c.x etc.
Just read the Javadoc:
http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Point.html
The underlying problem: In Java, operators like '+' and '-' are only allowed for primitive types (like byte, int, long) but not for objects (in general) and arrays.
Other languages allow for operator overloading, so in c++ you could define a '+' operation for Point objects and there your initial idea would compile and run. But that is not possible in Java.
The only exceptions are String (it's allowed to 'add' String objects) and the primitive wrappers like Integer and Double in Java 1.5+ (autoboxing converts them back to primitives)