Creating a System of Equations Method in Java - java

I am trying to establish a Java method to calculate the x and y coordinate based off of three given coordinates and distances. I used the following post:Determining The Coordinates Of A Point Based On Its Known Difference From Three Other Points for guidance. I just can't get this to work properly and don't really understand the math. With my given inputs I should be outputting (1,4), but instead output a bunch of different results depending on what I make d1, d2, d3.
public class Driver {
public static void main (String[] args)
{
double x1 = 1;
double y1 = 1;
double x2= 2;
double y2 = 1;
double x3= 3;
double y3 = 1;
double d1 = 3;
double d2 = 2;
double d3 = 1;
Main control = new Main();
control.GET_POINT(x1,y1,x2,y2,x3,y3,d1,d2,d3);
}
}
Class w/ Method:
public class Main {
public void GET_POINT(double x1, double y1,double x2,double y2,double x3,double y3, double r1, double r2, double r3){
double A = x1 - x2;
double B = y1 - y2;
double D = x1 - x3;
double E = y1 - y3;
double T = (r1*r1 - x1*x1 - y1*y1);
double C = (r2*r2 - x2*x2 - y2*y2) - T;
double F = (r3*r3 - x3*x3 - y3*y3) - T;
// Cramer's Rule
double Mx = (C*E - B*F) /2;
double My = (A*F - D*C) /2;
double M = A*E - D*B;
double x = Mx/M;
double y = My/M;
System.out.println(x);
System.out.println("and ");
System.out.println( y);
}
}

I guess that there is no problem with your program. The problem is that the four points that you chose have the same Y (the distance vectors are colinar). Therefore, M that is the determinant that is used by the cramer method to solve the linear system is always zero. So two divisions by zero arise in your program.
In this case, the solution is much simpler:
(x-xi)^2+(y-yi)^2=di^2
But y-yi=0. Threfore, x-xi=di.
So, I can write
x-x1=d1
x-x2=d2
x-x3=d3
Therefore, using any of these equations you get x=4 and Y is the same of the other points.
[PS: I think it is not a problem, but in the evaluation of Mx and My instead of dividing by 2 I would divide by 2.0 - just to be sure that integer division is not happening]
I hope I helped.
Daniel

Related

Distance between coordinates in Java

I'm trying to solve this problem.
Determine the distance between point (x1, y1) and point (x2, y2), and assign the result to pointsDistance.
I'll now present the original code along with my answer to the problem:
import java.util.Scanner;
public class CoordinateGeometry {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double x1;
double y1;
double x2;
double y2;
double pointsDistance;
double xDist;
double yDist;
pointsDistance = 0.0;
xDist = 0.0;
yDist = 0.0;
x1 = scnr.nextDouble();
y1 = scnr.nextDouble();
x2 = scnr.nextDouble();
y2 = scnr.nextDouble();
pointsDistance = Math.sqrt(x2 - Math.pow(x1, 2) + y2 - Math.pow(y1, 2)); //*Learning Square Rooots and powers*//
System.out.println(pointsDistance);
}
}
The desired outcomes from the inputs are not printing. For an example:
My value:
1
Expected value:
3
Where have I gone wrong?
Your formula is incorrect. It should be:
pointsDistance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
This is just an application of the Pythagorean theorem, and Java has a Math.hypot() convenience method that also protects against arithmetic overflow/underflow:
pointsDistance = Math.hypot(x2-x1, y2-y1);
Thanks to #LouisWasserman for the helpful comment.

Randomly generating a latlng within a radius yields a point out of bounds

I'm trying to generate a point within a radius and I'm getting incorrect values. Someone mind taking a look and telling me what I'm doing wrong for the longitude? This was a formulaic approach posted on a different question...
public static Location generateLocationWithinRadius(Location myCurrentLocation) {
return getLocationInLatLngRad(1000, myCurrentLocation);
}
protected static Location getLocationInLatLngRad(double radiusInMeters, Location currentLocation) {
double x0 = currentLocation.getLatitude();
double y0 = currentLocation.getLongitude();
Random random = new Random();
// Convert radius from meters to degrees
double radiusInDegrees = radiusInMeters / 111000f;
double u = random.nextDouble();
double v = random.nextDouble();
double w = radiusInDegrees * Math.sqrt(u);
double t = 2 * Math.PI * v;
double x = w * Math.cos(t);
double y = w * Math.sin(t);
double new_x = x / Math.cos(y0);
double new_y = y / Math.cos(x0);
double foundLatitude;
double foundLongitude;
boolean shouldAddOrSubtractLat = random.nextBoolean();
boolean shouldAddOrSubtractLon = random.nextBoolean();
if (shouldAddOrSubtractLat) {
foundLatitude = new_x + x0;
} else {
foundLatitude = x0 - new_x;
}
if (shouldAddOrSubtractLon) {
foundLongitude = new_y + y0;
} else {
foundLongitude = y0 - new_y;
}
Location copy = new Location(currentLocation);
copy.setLatitude(foundLatitude);
copy.setLongitude(foundLongitude);
return copy;
}
I should also say that for some reason the valid points yield a uniform line of coordinates when looking at them.
I think the latitude is processing correctly whereas the longitude is not.
Your code seems to be more or less based on an idea
which is presented at gis.stackexchange.com
and discussed some more there in this discussion
and in this discussion.
If we take a closer look at it based on those discussions then maybe it makes more sense.
To easily limit the values to a circle it uses the approach of randomizing a direction and a distance. First we get two random double values between 0.0 ... 1.0:
double u = random.nextDouble();
double v = random.nextDouble();
As the radius is given in meters and the calculations require degrees, it's converted:
double radiusInDegrees = radiusInMeters / 111000f;
The degrees vs. meters ratio of the equator is used here. (Wikipedia suggests 111320 m.)
To have a more uniform distribution of the random points the distance is compensated with a square root:
w = r * sqrt(u)
Otherwise there would be a statistical bias in the amount of points near the center vs. far from the center. The square root of 1 is 1 and 0 of course 0, so
multiplying the root of the random double by the intended max. radius always gives a value between 0 and the radius.
Then the other random double is multiplied by 2 * pi because there are 2 * pi radians in a full circle:
t = 2 * Pi * v
We now have an angle somewhere between 0 ... 2 * pi i.e. 0 ... 360 degrees.
Then the random x and y coordinate deltas are calculated with basic trigonometry using the random distance and random angle:
x = w * cos(t)
y = w * sin(t)
The [x,y] then points some random distance w away from the original coordinates towards the direction t.
Then the varying distance between longitude lines is compensated with trigonometry (y0 being the center's y coordinate):
x' = x / cos(y0)
Above y0 needs to be converted to radians if the cos() expects the angle as radians. In Java it does.
It's then suggested that these delta values are added to the original coordinates. The cos and sin are negative for half of the full circle's angles so just adding is fine. Some of the random points will be to the west from Greenwich and and south from the equator. There's no need to randomize
should an addition or subtraction be done.
So the random point would be at (x'+x0, y+y0).
I don't know why your code has:
double new_y = y / Math.cos(x0);
And like said we can ignore shouldAddOrSubtractLat and shouldAddOrSubtractLon.
In my mind x refers to something going from left to right or from west to east. That's how the longitude values grow even though the longitude lines go from south to north. So let's use x as longitude and y as latitude.
So what's left then? Something like:
protected static Location getLocationInLatLngRad(double radiusInMeters, Location currentLocation) {
double x0 = currentLocation.getLongitude();
double y0 = currentLocation.getLatitude();
Random random = new Random();
// Convert radius from meters to degrees.
double radiusInDegrees = radiusInMeters / 111320f;
// Get a random distance and a random angle.
double u = random.nextDouble();
double v = random.nextDouble();
double w = radiusInDegrees * Math.sqrt(u);
double t = 2 * Math.PI * v;
// Get the x and y delta values.
double x = w * Math.cos(t);
double y = w * Math.sin(t);
// Compensate the x value.
double new_x = x / Math.cos(Math.toRadians(y0));
double foundLatitude;
double foundLongitude;
foundLatitude = y0 + y;
foundLongitude = x0 + new_x;
Location copy = new Location(currentLocation);
copy.setLatitude(foundLatitude);
copy.setLongitude(foundLongitude);
return copy;
}
It is hard for me to provide you with a pure Android solution as I never used those API. However I am sure you could easily adapt this solution to generate a random point within a given radius from an existing point.
The problem is solved in a two dimensions space however it is easy to extend to support altitude as well.
Please have a look at the code below. It provides you with a LocationGeneratoras well as my own Location implementation and an unit test proving that it works.
My solution is based on solving the circle equation (x-a)^2 + (y-b)^2 = r^2
package my.test.pkg;
import org.junit.Test;
import java.util.Random;
import static org.junit.Assert.assertTrue;
public class LocationGeneratorTest {
private class Location {
double longitude;
double latitude;
public Location(double longitude, double latitude) {
this.longitude = longitude;
this.latitude = latitude;
}
}
private class LocationGenerator {
private final Random random = new Random();
Location generateLocationWithinRadius(Location currentLocation, double radius) {
double a = currentLocation.longitude;
double b = currentLocation.latitude;
double r = radius;
// x must be in (a-r, a + r) range
double xMin = a - r;
double xMax = a + r;
double xRange = xMax - xMin;
// get a random x within the range
double x = xMin + random.nextDouble() * xRange;
// circle equation is (y-b)^2 + (x-a)^2 = r^2
// based on the above work out the range for y
double yDelta = Math.sqrt(Math.pow(r, 2) - Math.pow((x - a), 2));
double yMax = b + yDelta;
double yMin = b - yDelta;
double yRange = yMax - yMin;
// Get a random y within its range
double y = yMin + random.nextDouble() * yRange;
// And finally return the location
return new Location(x, y);
}
}
#Test
public void shoulRandomlyGeneratePointWithinRadius () throws Exception {
LocationGenerator locationGenerator = new LocationGenerator();
Location currentLocation = new Location(20., 10.);
double radius = 5.;
for (int i=0; i < 1000000; i++) {
Location randomLocation = locationGenerator.generateLocationWithinRadius(currentLocation, radius);
try {
assertTrue(Math.pow(randomLocation.latitude - currentLocation.latitude, 2) + Math.pow(randomLocation.longitude - currentLocation.longitude, 2) < Math.pow(radius, 2));
} catch (Throwable e) {
System.out.println("i= " + i + ", x=" + randomLocation.longitude + ", y=" + randomLocation.latitude);
throw new Exception(e);
}
}
}
}
NOTE:
This is just a generic solution to obtain a random point inside a circle with the center in (a, b) and a radius of r that can be used to solve your problem and not a straight solution that you can use as such. You most likely will need to adapt it to your use case.
I believe this is a natural solution.
Regards
Kotlin version of Markus Kauppinen answer
fun Location.getRandomLocation(radius: Double): Location {
val x0: Double = longitude
val y0: Double = latitude
// Convert radius from meters to degrees.
// Convert radius from meters to degrees.
val radiusInDegrees: Double = radius / 111320f
// Get a random distance and a random angle.
// Get a random distance and a random angle.
val u = Random.nextDouble()
val v = Random.nextDouble()
val w = radiusInDegrees * sqrt(u)
val t = 2 * Math.PI * v
// Get the x and y delta values.
// Get the x and y delta values.
val x = w * cos(t)
val y = w * sin(t)
// Compensate the x value.
// Compensate the x value.
val newX = x / cos(Math.toRadians(y0))
val foundLatitude: Double
val foundLongitude: Double
foundLatitude = y0 + y
foundLongitude = x0 + newX
val copy = Location(this)
copy.latitude = foundLatitude
copy.longitude = foundLongitude
return copy
}
Longitude and Latitude uses ellipsoidal coordinates so for big radius (hundred meters) the error using this method would become sinificant. A possible trick is to convert to Cartesian coordinates, do the radius randomization and then transform back again to ellipsoidal coordinates for the long-lat. I have tested this up to a couple of kilometers with great success using this java library from ibm. Longer than that might work, but eventually the radius would fall off as the earth shows its spherical nature.

Function for finding the distance between a point and an edge in java

Does anyone have a function in java for finding the shortest distance between a point and a line segment/edge? Every example I find is in another language and uses a bunch of sub functions. It can't be based on the assumption that they are perpendicular.
Update
I ported over a python function to java. If anyone is good at math and can verify I would appreciate it. x and y is the point, and other params are for the line segment.
public float pDistance(float x, float y, float x1, float y1, float x2, float y2) {
float A = x - x1;
float B = y - y1;
float C = x2 - x1;
float D = y2 - y1;
float dot = A * C + B * D;
float len_sq = C * C + D * D;
float param = -1;
if (len_sq != 0) //in case of 0 length line
param = dot / len_sq;
float xx, yy;
if (param < 0) {
xx = x1;
yy = y1;
}
else if (param > 1) {
xx = x2;
yy = y2;
}
else {
xx = x1 + param * C;
yy = y1 + param * D;
}
float dx = x - xx;
float dy = y - yy;
return (float) Math.sqrt(dx * dx + dy * dy);
}
We can simplify things a bit. You don't need to calculate param. What you can do is find a vector v at right angles to the line. The take the dot product of that with the vector (A,B). In 2D its easy enough to find the vector orthogonal to (C,D), its just (-D,C).
public float pDistance(float x, float y, float x1, float y1, float x2, float y2) {
float A = x - x1; // position of point rel one end of line
float B = y - y1;
float C = x2 - x1; // vector along line
float D = y2 - y1;
float E = -D; // orthogonal vector
float F = C;
float dot = A * E + B * F;
float len_sq = E * E + F * F;
return (float) Math.abs(dot) / Math.sqrt(len_sq);
}
If you are worried about performance is can be easier to work with the squared distances then the last line would be
return (float) dot * dot / len_sq;
This saves having to calculate a square root. So if you want to calculate the closest edge, find the squared distances to each edge and select the smallest.
This function find the distance to the infinite line rather than the line segment. This may not be what you want. The solution in the question differs in what happens if the point is beyond the two ends of the line segment. There it find the distance to the closest end point.
From http://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line
The distance (or perpendicular distance) from a point to a line is the
shortest distance from a point to a line in Euclidean geometry. It is
the length of the line segment which joins the point to the line and
is perpendicular to the line.
You say that "It can't be based on the assumption that they are perpendicular.", but the shortest distance between a point and a line segment represents another line which is perpendicular to the original line. Hence it is the height of the triangle formed by A B and C, where A - the point, B and C are the end points of the line segment.
We know the coordinates of all three points, therefore we can obtain lengths of sides of the triangle. Using Heron's formula: https://www.mathsisfun.com/geometry/herons-formula.html we can obtain the area which is also equal to 0.5 * b * h from: https://www.mathsisfun.com/algebra/trig-area-triangle-without-right-angle.html
private static float distBetweenPointAndLine(float x, float y, float x1, float y1, float x2, float y2) {
// A - the standalone point (x, y)
// B - start point of the line segment (x1, y1)
// C - end point of the line segment (x2, y2)
// D - the crossing point between line from A to BC
float AB = distBetween(x, y, x1, y1);
float BC = distBetween(x1, y1, x2, y2);
float AC = distBetween(x, y, x2, y2);
// Heron's formula
float s = (AB + BC + AC) / 2;
float area = (float) Math.sqrt(s * (s - AB) * (s - BC) * (s - AC));
// but also area == (BC * AD) / 2
// BC * AD == 2 * area
// AD == (2 * area) / BC
// TODO: check if BC == 0
float AD = (2 * area) / BC;
return AD;
}
private static float distBetween(float x, float y, float x1, float y1) {
float xx = x1 - x;
float yy = y1 - y;
return (float) Math.sqrt(xx * xx + yy * yy);
}
I do not know how correct it is, hopefully a real mathematician can correct or back up this solution
If your line passes through two points, you can determine the equation of the line exactly.
If your line is ax + by + c = 0 and your point is (x0, y0), then the distance is given by :
This gives the shortest distance between any line and a point. (a, b, c are real constants)
Edit : In order to find the exact equation from two points on the line, the steps are :
`y − y1 = m(x − x1)` where m is the slope of the line.
Simplifying from this, a = -m, b = 1 and c = m*x1 - y1
If you do not want to implement all this by yourself I can recommend to use JTS. Use the distance method from LineSegment (for lines) or Coordinate (for points) accordingly. Given Points p1 and p2 for your Line and a Point p3 (that you want to calculate the distance) the code would look like that:
// create Line
LineSegment ls = new LineSegment(p1.getX(), p1.getY(), p2.getX(), p2.getY());
//calculate distance between Line and Point
double distanceLinePoint = ls.distance(new Coordinate(p3.getX(), p3.getY()));
// calculate distance between Points (p1 - p3)
double distanceBetweenPoints = new Coordinate(p1.getX(), p1.getY()).distance(new Coordinate(p3.getX(), p3.getY()));

Finding length and angles of a triangle

My job is to compute the following properties of a given triangle: lengths of all sides, angles at all corners, the perimeter and the area. I have a Triangle class and a Triangle tester class. I THINK I have coded the perimeter and area correctly? But I am beginning to think instead of setting a constant variable side for my perimeter I should be using the lengths of all sides to find my perimeter as well. What I am stuck on is finding the lengths and the angles. For some reason when I run my tester class they all come out as 1.0. Any advice would be appreciated! Thank you!
import java.util.Scanner;
public class Triangle
{
Scanner in = new Scanner(System.in);
/**
* Variables
*/
double x1;
double x2;
double x3;
double y1;
double y2;
double y3;
double lengthA;
double lengthB;
double lengthC;
double angleA;
double angleB;
double angleC;
double area;
double perimeter;
double base;
double height;
double p;
/**
Constructs x and y coordinates
#param x1, x2, x3 to x1, x2, x3
#param y1, y2, y3 to y1, y2, y3
*/
public Triangle(double x1, double x2, double x3, double y1, double y2, double y3)
{
this.x1 = x1;
this.x2 = x2;
this.x3 = x3;
this.y1 = y1;
this.y2 = y2;
this.y3 = y3;
}
/**
*Find lengths of all sides
*/
public double getLengthA()
{
lengthA = Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2));
return lengthA;
}
public double getLengthB()
{
lengthB = Math.sqrt(Math.pow((x3 - x2), 2) + Math.pow((y3 - y2), 2));
return lengthB;
}
public double getLengthC()
{
lengthC = Math.sqrt(Math.pow((x1 - x3), 2) + Math.pow((y1 - y3), 2));
return lengthC;
}
/**
* Find angles at all corners
#return angles at all corners
*/
public double getAngleA()
{
angleA = lengthA + lengthB + lengthC - (lengthB * lengthC);
return angleA;
}
public double getAngleB()
{
angleB = lengthB + lengthA + lengthC - (lengthA * lengthC);
return angleB;
}
public double getAngleC()
{
angleC = lengthC + lengthA + lengthB - (lengthA * lengthB);
return angleC;
}
/**
* Constant Variables
*/
public Triangle()
{
base = 5;
height = 15;
}
/**
* Find perimeter of triangle
*/
public double getPerimeter()
{
perimeter = lengthA + lengthB + lengthC;
return perimeter;
}
public double getHalfPerimeter()
{
p = perimeter / 2;
return p;
}
/**
* Find area of triangle
*/
public double getArea()
{
double area = Math.sqrt(p * (p - lengthA) * (p - lengthB) * (p - lengthC));
return area;
}
}
Here is my tester class:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class TriangleSimulator
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
String input = JOptionPane.showInputDialog("Enter X coordinate for the first corner of the triangle: ");
double x1 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter Y coordinate for the first corner of the triangle: ");
double y1 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter X coordinate for the second corner of the triangle: ");
double x2 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter Y coordinate for the second corner of the triangle: ");
double y2 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter X coordinate for the third corner of the triangle: ");
double x3 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter Y coordinate for the third corner of the triangle: ");
double y3 = Double.parseDouble(input);
Triangle t = new Triangle(x1, x2, x3, y1, y2, y3);
System.out.println("Length A is: " + t.getLengthA());
System.out.println("Length B is: " + t.getLengthB());
System.out.println("Length C is: " + t.getLengthC());
System.out.println("Angle A is: " + t.getAngleA());
System.out.println("Angle B is: " + t.getAngleB());
System.out.println("Angle C is: " + t.getAngleC());
System.out.println("Area: " + t.getArea());
System.out.println("Perimeter: " + t.getPerimeter());
in.close();
}
}
You're showing JOptionPanes that prompt the user for input, but you're not getting the input and you're thus not using the input to set the state of your Triangle, creating a default Triangle object using its parameterless constructor. Understand that there's no magic in Java programming, and your Triangle object will not magically know what numbers the user has entered and change itself accordingly. Instead you must give that information into your Triangle.
What you must do is assign the results returned from the JOptionPanes, parse them into doubles, and then use those numbers to create a Triangle, using the constructor that takes numeric value parameters, not the default constructor. Do this, and you should be good.
e.g.
String input = JOptionPane.showInputDialog("Enter X coordinate for the first corner of the triangle: ");
double x1 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter Y coordinate for the first corner of the triangle:
double y1 = Double.parseDouble(input);
//.... etc repeat...
Triangle triangle = new Triangle(x1, x2, x3, y1, y2, y3);
Edit
This constructor ignores the values being passed in:
public Triangle(double x1, double x2, double x3, double y1, double y2, double y3)
{
x1 = 0;
x2 = 0;
x3 = 0;
y1 = 0;
y2 = 0;
y3 = 0;
}
A constructor like the one you'll need, should take the values passed in, and use those values to set class fields. For instance here:
public class Foo {
private int bar; // the bar field
public Foo(int bar) {
this.bar = bar;
}
}
Note that I use this.bar above so that Java knows that I want to set the bar field with the value held by the bar parameter (the bar without the this). You will need to do something similar only with 6 parameters, not one.
Then you do all your calculations in a separate block of code called an initializer block:
{
/**
* Find lengths of all sides
*/
lengthA = Math.pow(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2) * .05, lengthA);
lengthB = Math.pow(Math.pow((x3 - x2), 2) + Math.pow((y3 - y2), 2) * .05, lengthB);
lengthC = Math.pow(Math.pow((x1 - x3), 2) + Math.pow((y1 - y3), 2) * .05, lengthC);
}
This code gets called before your constructor, and so even if you set your Triangles fields correctly, this code wouldn't work. You don't want to use initializer blocks, and you can forget I even mentioned them other than to tell you not to use them. Instead do your calculations inside your constructor, and do so after setting all your fields.
Note that I've purposely not posted a solution to your problem because I firmly believe that what most of us need is to understand the concepts underlying any problems we are having, and then use that understanding to create our own code solutions.
Most important, read your texts, no better, study your texts, because the mistakes you're making involve foundational concepts, and show that you don't yet understand these concepts and have resorted to guessing. This will never work, as you need to understand all this and understand it well if you're going to be able to progress in this course.
Good luck!
Edit 2
For Tom, run this:
public class TestInitializerBlock {
public TestInitializerBlock() {
System.out.println("Inside of constructor");
}
{
System.out.println("Inside of initializer block");
}
public static void main(String[] args) {
new TestInitializerBlock();
}
}

Floating point accuracy [duplicate]

This question already has answers here:
Floating point arithmetic not producing exact results [duplicate]
(7 answers)
Closed 9 years ago.
I am writing a method which calculates the equation of a 2D Line in the form a*x+b*y=1
//Given two points, find the equation of the line by solving two linear equations and then test the result. (For simplicity, assume that delta !=0 here)
private boolean solveAndRetry(float x1,float y1, float x2,float y2) {
float delta = x1 * y2 - x2 * y1;
float deltaA = y2 - y1;
float deltaB = x1 - x2;
float a = deltaA / delta;
float b = deltaB / delta;
float c = 1;
//test
if (a * x2 + b * y2 == c) {
System.out.println("ok");
return true;
}
else {
System.out.println(a * x2 + b * y2-c);
return false;
}
}
When I ran it, I was expecting there would be all "ok"s, but that's not the case and I don't know why
public static void main(String[] args) {
for (float x = 0; x < 10; x += 0.01f) {
solveAndRetry(1, -1, x, 2);
}
}
Here are some lines in the result
ok
ok
ok
ok
ok
ok
ok
ok
-5.9604645E-8
ok
-5.9604645E-8
ok
ok
ok
1.1920929E-7
ok
ok
-5.9604645E-8
ok
A float has an accuracy of 6 to 7 decimal digits. Since rounding errors cannot be avoided, your results are as good as it can get.
Normally, you would never compare floating point numbers for equality. Instead of x == y always use a comparison with an interval:
Math.abs(x - y) < eps
for a suitably chosen eps.

Categories