I have been searching the internet for about a day and I can not seem to find an algorithm to find all points within a bounding box.
Picture:
The accuracy also needs to be 8 decimal digits long.
Example:
(0,0)
(0,0.00000001)
(0,0.00000002)
etc..
(80,80.45356433)
I don't know what exactly you mean by finding all points inside a box. There is just too many!
I would suggest using an Identifier function, i.e., given a point (x, y), I(x, y) = 1 if and only if the point (x, y) is inside your box.
A call to the identifier in your example requires $4$ comparisons.
public class Box {
/**
* Identifier function.
* #param x x-coordinate of input point
* #param y y-coordinate of input point
* #return True if and only if the given point is inside the box.
*/
public boolean IsInside(double x, double y) {
return (this.x_min <= x) && (this.x_max >= x) &&
(this.y_max >= y) && (this.y_min <= y);
}
double x_min, x_max, y_min, y_max; // or do it with left top width and height
}
I hope it helps.
long p = (long)Math.pow(10, 8);
long start = 90 * p;
long end = 180 * p;
for (long i = start; i < end; i++) {
for (long j = start; j < end; j++) {
System.out.println("(" + (double)i / p + "," + (double)j / p + ")");
}
}
will take a while
Related
I want to create a "spiral effect" with particles (or any entities) in Java.
I'm new to objective programming (and also Java), so I started with something easier. I firstly created a Path object that has a value of Locations[] signed to it, it gets from the user a: Start location, End location, and double value, that tells him, how much space between each location in the path he has.
private void setLocations() {
//initialize vars
Location start = getStart();
World world = start.getWorld();
Location[] locations = new Location[amount];
double x = start.getX();
double y = start.getY();
double z = start.getZ();
//loop that will set values for locations
for (int i = 0; i < amount; i++) {
locations[i] = new Location(
world,
x + dividedDistanceX * (i + 1),
y + dividedDistanceY * (i + 1),
z + dividedDistanceZ * (i + 1)
);
}
this.locations = locations;
}
Now you might be asking what is the amount? So simply it's the number of points that are created when the object is initialized. It's simple math like getting the longest distance from point to point, and then dividing it by the value of space between each point.
Now the situation gets a little more complicated, so I prepared graphics for you:)
I want to rotate points around the longest axis to form some form of a spiral, and I want from user to set the maximum distance between the starting point and the new one.
Something like this:
And another graph of the sinusoid around one vector (x, y)
Honestly, I need some help.
Here's GitHub object link
Things I know I need to do:
Get the axis around which I will rotate point (it's the longest distance between points)
Add some value to the rest values (x+something, y+something)
Add angle, that point will rotate with, (for example each point will be rotated by 22,5).
Okay, so i did it, it wasn't even that hard:
public Location[] createSpiral(double radius, float angle, Location[] path) {
final int length = path.length;
Location[] result = path.clone();
Location start = path[0];
Location end = path[length - 1];
double startX = start.getX();
double startY = start.getY();
double startZ = start.getZ();
double endX = end.getX();
double endY = end.getY();
double endZ = end.getZ();
double distanceX = setDistance(startX, endX);
double distanceY = setDistance(startY, endY);
double distanceZ = setDistance(startZ, endZ);
double highestOffset = getHighestOffset(new double[]{distanceX, distanceY, distanceZ});
if (highestOffset == abs(distanceX)) {
for (int i = 0; i < length; i++) {
double sin = radius * sin(angle * i / length);
double cos = radius * cos(angle * i / length);
result[i].setY(result[i].getY() + cos);
result[i].setZ(result[i].getZ() + sin);
}
} else if (highestOffset == abs(distanceY)) {
for (int i = 0; i < length; i++) {
double sin = radius * sin(angle * i / length);
double cos = radius * cos(angle * i / length);
result[i].setX(result[i].getX() + cos);
result[i].setZ(result[i].getZ() + sin);
}
} else if (highestOffset == abs(distanceZ)) {
for (int i = 0; i < length; i++) {
double sin = radius * sin(angle * i / length);
double cos = radius * cos(angle * i / length);
result[i].setX(result[i].getX() + cos);
result[i].setY(result[i].getY() + sin);
}
} else {
return path;
}
return result;
}
It's just
double sin = radius * sin(angle * i / length);
double cos = radius * cos(angle * i / length);
and adding those values to corresponding X, Y if Z has the highest distance from a location, etc.
The rest of the code and methods are located in the GitHub link above.
I found a practice java class and I am trying to get all points on the line segment such that for every point x and y are both integers but I am having trouble of implementing it. I am just looking for a formula I can use to solve the problem. or explain me how it get point (3,2). Thanks
/**
*
* #return an array containing all points on the line segment such that for every point in the array,
* both x and y are integers
* For example, if there is a line from (1,1) to (5,3), the only other point for which both x and y are
* integers is (3,2). Thus the method should return the array containing (1,1), (3,2) and (5,3)
* The order of points in the array returned should be from the point with lower x
* (use Point a as the starting point in case a.x == b.x).
*
* Hence if a = (5,1) and b=(1,3), the method returns an array such that
* first item is (1,3), second is (3,2) and third is (5,1)
*/
public Point[] getPointsOnCrosshair() {
Point[] points = new Point[20];
int counter = 0;
//getting slope of the line
double rise = this.b.y - this.a.y;
double run = this.b.x - this.a.x;
double m = rise/run;
System.out.println(m);
//getting value of c -> y = mx + c
double c = a.y - (m * a.x);
int start = 0;
int end = 0;
if (b.x >= a.x){
start = a.x;
end = b.x;
}
else{
start = b.x;
end = a.x;
}
// slope intercept y - y1 = m (x-x1)
// y = (m (x-x1)) + y1
double y = 0;
for (int a = start; a <= end; a++){
y = (m * a) + c;
if (y == (int) y){
points[counter] = new Point(a, (int) y);
counter++;
}
}
return points;
}
First, determine if the line is mostly horizontal or mostly vertical.
▉ ▉ ▉
▉ ▉ ▉
▉ ▉ ▉
▉
▉
▉
If it is mostly horizontal, you iterate x from a.x to b.x and calculate y.
If it is mostly vertical, you iterate y from a.y to b.y and calculate x.
I'll leave it to you to build the right formula, or to go find it on the web, i.e. do some research.
Brute force solution is really simple:
int p1x = 1;
int p1y = 1;
int p2x = 5;
int p2y = 3;
int xdiff = p2x - p1x;
int ydiff = p2y - p1y;
for (int x = p1x + 1; x < p2x; ++x) {
float y = ((float) x - p1x) / xdiff * ydiff + p1y;
if (((int) y) == y) { // check if xx.0
System.out.print(x);
System.out.print(", ");
System.out.println((int)y);
}
}
But I'm sure there's a more elegant way, maybe using prime factorization
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Here is the error i'm getting:
airfoilNumber.java:5: error: cannot access airfoil
private airfoil myAirfoil = new airfoil();
^
bad class file: ./airfoil.class
class file contains wrong class: airfoil.airfoil
Please remove or make sure it appears in the correct subdirectory of the classpath.
Here is my main class:
import java.util.Scanner;
public class airfoilNumber
{
private airfoil myAirfoil = new airfoil();
public static void main(String[] args)
{
Scanner numNaca1 = new Scanner(System.in); //make a scanner and prompt user for their desired NACA number
System.out.println("What is your NACA number?"); //prompt user for NACA number
int numNaca = numNaca1.nextInt(); //apply the number to numNaca
new airfoil(numNaca); //call out airfoil class and run calculations
}
}
Here is my calculator class:
package airfoil;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class airfoil
{
private static final int numOfCoord = 250;
double dx = 1
.0 / numOfCoord;
private double m; // maximum camber in % of chord
private double p; // chordwise position of max ord., 10th of chord
private double t; // thickness in % of the cord
private String nacaNum; // NACA number - 4 digits
private double[][] coordinates; // Coordinates of the upper half or lower half of the airfoil
private double[][] meanLine; // mean line coordinates
public airfoil(String number) {
nacaNum = number;
m = Double.parseDouble(nacaNum.substring(0,1)) / 100.0;
p = Double.parseDouble(nacaNum.substring(1,2)) / 10.0;
t = Double.parseDouble(nacaNum.substring(2,4)) / 100.0;
meanLine = new double[2][numOfCoord]; // x values row 0, y values row 1
// x upper = row 0,
// y upper = row 1,
// x lower = row 2,
// y lower = row 3
coordinates = new double [4][numOfCoord];
System.out.println("NACA: " + nacaNum);
System.out.println("Number of coordinates: " + numOfCoord);
calcMeanLine();
calcAirfoil();
}
/*
* Calculates the values for the mean line forward of the maximum
* ordinate and aft of the maximum ordinate.
*/
private void calcMeanLine() {
double x = dx;
int j = 0;
// fwd of max ordinate
while (x <= p) {
meanLine[0][j] = x;
meanLine[1][j] = (m / (p * p))*(2*p*x - (x*x));
x += dx;
j++;
}
// aft of max ordinate
while (x <= 1.0 + dx) {
meanLine[0][j] = x;
meanLine[1][j] = (m / ((1 - p) * (1 - p))) *
((1 - 2*p) + 2*p*x - x * x);
x += dx;
j++;
}
} // end calcMeanLine
/*
* Calculate the upper and lower coordinates of the airfoil surface.
*/
private void calcAirfoil() {
double theta; // arctan(dy_dx)
double dy; // derivative of mean line equation
double yt, ml; // thickness and meanline values, respectively
double x = dx; // x-value w.r.t. chord
int j = 0; // counter for array
// calculate upper/lower surface coordinates fwd of max ordinate
while (x <= p) {
dy = (m / (p*p)) * (2*p - 2*x);
theta = Math.atan(dy);
yt = thicknessEQ(x);
ml = meanLine[1][j];
// upper surface coordinates;
coordinates[0][j] = x - yt * Math.sin(theta);
coordinates[1][j] = ml + yt * Math.cos(theta);
// lower surface coordinates
coordinates[2][j] = x + yt*Math.sin(theta);
coordinates[3][j] = ml - yt * Math.cos(theta);
x += dx;
j++;
}
// calculate the coordinates aft of max ordinate
while (x <= 1.0 + dx) {
dy = (m / ((1 - p) * (1 - p))) * ((2 * p) - (2 * x));
theta = Math.atan(dy);
yt = thicknessEQ(x);
ml = meanLine[1][j];
// upper surface coordinates;
coordinates[0][j] = x - yt * Math.sin(theta);
coordinates[1][j] = ml + yt * Math.cos(theta);
// lower surface coordinates
coordinates[2][j] = x + yt * Math.sin(theta);
coordinates[3][j] = ml - yt * Math.cos(theta);
x += dx;
j++;
}
System.out.println("j = " + j);
} // end calcAirfoil
/*
* Thickness equation
*/
private double thicknessEQ(double x) {
return ((t / 0.2) * (0.2969 * Math.sqrt(x) - (0.126 * x) -
(0.3526 * x * x) + (0.28430 * x * x * x) -
(0.1015 * x * x * x * x)));
}
public String toString() {
String str = "";
NumberFormat df = new DecimalFormat("0.0000");
System.out.println("Xu\tYu\tXl\tYl");
for (int j = 0; j < numOfCoord; j++) {
str += df.format(coordinates[0][j]) + "\t" +
df.format(coordinates[1][j]) + "\t" +
df.format(coordinates[2][j]) + "\t" +
df.format(coordinates[3][j]) + "\n";
}
return str;
}
/*
* Return the coordinates array
*/
public double[][] getCoordinates() { return coordinates; }
public int getSize() { return numOfCoord; }
} // end Airfoil class
Here is what i've tried:
Moving the airfoil.class file around from place to place to get it to work
use "new airfoil ("");" by itself, still gives me the same error
used any other type of code to call out my calculator class, same error.
I don't know what else to change. I don't know what it's telling me about "Wrong class airfoil.airfoil", that might be able to lead me to the solution.
What am i doing wrong here?
error is in:
new airfoil(numNaca); //call out airfoil class and run calculations
delete this line and call:
myAirfoil(numNaca);
new airfoil make new instance of youre class, not run calculations.
New instance exist in code, see line:
private airfoil myAirfoil = new airfoil();
and acces to this is myAirfoil.
You have the following class structure:
package airfoil;
public class airfoil {
...
}
public class airfoilNumber {
...
}
This needs to be reflected on the file system like this:
MyProject Project's top level directory
+-airfoilNumber.java
+-airfoil directory for "airfoil" package
+-airfoil.java
In addition, you then need to import airfoil.airfoil in your airfoilNumber class:
import airfoil.airfoil;
public class airfoilNumber {
}
With this setup, you can compile the two classes from within the project's top level directory with
C:> javac *.java
As a side comment, class names should start with uppercase letters. I kept the names from the question since casing mismatches between the class definition and its containing .java file can lead to other issues which are difficult to track, at least on MS Windows.
Once that is done, you need to fix the constructors of your airfoil class. There is currently only one constructor which takes a String argument, but you call it as follows:
private airfoil myAirfoil = new airfoil();
// does not compile - no non-arg constructor available
...
new airfoil(numNaca);
// does not compile - numNaca is int, constructor expects String
I am working through the solution to the following problem:
Given two squares on a two-dimensional plane, find a line that would
cut these two squares in half. Assume that the top and the bottom
sides of the square run parallel to the x-axis.
This is the solution in the book:
public class Square {
public double left;
public double top;
public double bottom;
public double right;
public double size;
public Square(double left, double top, double size) {
this.left = left;
this.top = top;
this.bottom = top + size;
this.right = left + size;
this.size = size;
}
public Point middle() {
return new Point((this.left + this.right)/2.0, (this.top + this.bottom)/2.0);
}
public boolean contains(Square other) {
if (this.left <= other.left && this.right >= other.right && this.top <= other.top && this.bottom >= other.bottom) {
return true;
}
return false;
}
/* Return the point where the line segment connecting mid1 and
* mid2 intercepts the edge of square 1. That is, draw a line
* from mid2 to mid1, and continue it out until the edge of
* the square. */
public Point extend(Point mid1, Point mid2, double size) {
/* Find what direction the line mid2 -> mid1 goes */
double xdir = mid1.x < mid2.x ? -1 : 1;
double ydir = mid1.y < mid2.y ? -1 : 1;
/* If mid1 and mid2 have the same x value, then the slope
* calculation will throw a divide by 0 exception. So, we
* compute this specially. */
if (mid1.x == mid2.x) {
return new Point(mid1.x, mid1.y + ydir * size / 2.0);
}
double slope = (mid1.y - mid2.y) / (mid1.x - mid2.x);
double x1 = 0;
double y1 = 0;
/* Calculate slope using the equation (y1 - y2) / (x1 - x2).
* Note: if the slope is “steep” (>1) then the end of the
* line segment will hit size / 2 units away from the middle
* on the y axis. If the slope is “shallow” (<1) the end of
* the line segment will hit size / 2 units away from the
* middle on the x axis. */
if (Math.abs(slope) == 1) {
x1 = mid1.x + xdir * size / 2.0;
y1 = mid1.y + ydir * size / 2.0;
} else if (Math.abs(slope) < 1) {
x1 = mid1.x + xdir * size / 2.0;
y1 = slope * (x1 - mid1.x) + mid1.y;
} else {
y1 = mid1.y + ydir * size / 2.0;
x1 = (y1 - mid1.y) / slope + mid1.x;
}
return new Point(x1, y1);
}
public Line cut(Square other) {
/* Calculate where a line between each middle would collide with the edges of the squares */
Point p1 = extend(this.middle(), other.middle(), this.size);
Point p2 = extend(this.middle(), other.middle(), -1 * this.size);
Point p3 = extend(other.middle(), this.middle(), other.size);
Point p4 = extend(other.middle(), this.middle(), -1 * other.size);
/* Of above points, find start and end of lines. Start is farthest left (with top most as a tie breaker)
* and end is farthest right (with bottom most as a tie breaker */
Point start = p1;
Point end = p1;
Point[] points = {p2, p3, p4};
for (int i = 0; i < points.length; i++) {
if (points[i].x < start.x || (points[i].x == start.x && points[i].y < start.y)) {
start = points[i];
} else if (points[i].x > end.x || (points[i].x == end.x && points[i].y > end.y)) {
end = points[i];
}
}
return new Line(start, end);
}
public String toString() {
return "(" + left + ", " + top + ")|(" + right + "," + bottom + ")";
}
}
I have the following questions:
What is the size parameter in the extend function? The size of what? A side? The entire square (how can we quantify the size of the entire square?) Area?
In the cut() function, what are p1 through p4 ultimately doing? And why do we need 4 points to do it?
As I understand the problem, it's necessary and sufficient for the line to connect the two centres.
Assume that the top and the bottom sides of the square run parallel to the x-axis.
I'm not aware of why this assumption is necessary.
This answer might not be relevant to the TS. But in case if you are also wondering about this answer, the parameter "size" is misleading - it is referring to the length of the square (Eg. 3x3 square has the length of 3.) Why four points? Because the question assumes that the line here represents the two "farest" points that cut across two squares. Each square has two points that has the potential to become start/end of the line.
I've been trying to implement trapezoid rule for double integral. I've tried many approaches, but I can't get it to work right.
static double f(double x) {
return Math.exp(- x * x / 2);
}
// trapezoid rule
static double trapezoid(double a, double b, int N) {
double h = (b - a) / N;
double sum = 0.5 * h * (f(a) + f(b));
for (int k = 1; k < N; k++)
sum = sum + h * f(a + h*k);
return sum;
}
I understand the method for a single variable integral, but I don't know how to do it for a 2D integral, say: x + (y*y).
Could someone please explain it briefly?
If you're intent on using the trapezoid rule then you would do it like so:
// The example function you provided.
public double f(double x, double y) {
return x + y * y;
}
/**
* Finds the volume under the surface described by the function f(x, y) for a <= x <= b, c <= y <= d.
* Using xSegs number of segments across the x axis and ySegs number of segments across the y axis.
* #param a The lower bound of x.
* #param b The upper bound of x.
* #param c The lower bound of y.
* #param d The upper bound of y.
* #param xSegs The number of segments in the x axis.
* #param ySegs The number of segments in the y axis.
* #return The volume under f(x, y).
*/
public double trapezoidRule(double a, double b, double c, double d, int xSegs, int ySegs) {
double xSegSize = (b - a) / xSegs; // length of an x segment.
double ySegSize = (d - c) / ySegs; // length of a y segment.
double volume = 0; // volume under the surface.
for (int i = 0; i < xSegs; i++) {
for (int j = 0; j < ySegs; j++) {
double height = f(a + (xSegSize * i), c + (ySegSize * j));
height += f(a + (xSegSize * (i + 1)), c + (ySegSize * j));
height += f(a + (xSegSize * (i + 1)), c + (ySegSize * (j + 1)));
height += f(a + (xSegSize * i), c + (ySegSize * (j + 1)));
height /= 4;
// height is the average value of the corners of the current segment.
// We can use the average value since a box of this height has the same volume as the original segment shape.
// Add the volume of the box to the volume.
volume += xSegSize * ySegSize * height;
}
}
return volume;
}
Hope this helps. Feel free to ask any questions you may have about my code (warning: The code is untested).
Many ways to do it.
If you already know it for 1d you could make it like this:
write a function g(x) that calculates the 1d integral over f(x,y) for a fixed x
then integrate the 1d integral over g(x)
Success :)
That way you can basically have as many dimensions as you like. Though it scales poorly. For larger problems it might be neccesary to use monte carlo integration.
Consider using the class jhplot.F2D from the DataMelt Java program. You can integrate and visualize 2D functions doing something like:
f1=F2D("x*y",-1,1,-1,1) # define in a range
print f1.integral()