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
Alongside with my main class, i want to output the table with the points of the airfoil to the command line, but right now some of the system print functions aren't working. here is my calc 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
This part of the class is supposed to print a table, but it isnt doing anything:
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;
}
So what can I do to make these things print correctly?
Your System.out.println("Xu\tYu\tXl\tYl"); code prints the following: Xu Yu Xl Yl because you did not add any variables to it. You could change it to:
public String toString() {
String str = "";
NumberFormat df = new DecimalFormat("0.0000");
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";
}
System.out.println(str);
return str;
}
Anyway, don't print in toString() function. toString() shouldn't print anything, it should just return the String so that you can print it or do whatever you want with it.
Airfoil airfoil = new Airfoil(); // Yes, first letter uppercase recommended
// do stuff
System.out.println(airfoil.toString());
EDIT: It works for me (I think). I used the input 1000 (by the way, you should use try/catch for numbers with 3 characters or less or it will crash), and this is the output I got (only the beginning and ending), as it's long.
NACA: 1000
Number of coordinates: 250
j = 250
0.0040 0.0100 0.0040 0.0100
0.0080 0.0100 0.0080 0.0100
0.0120 0.0100 0.0120 0.0100
[...]
0.9920 0.0002 0.9920 0.0002
0.9960 0.0001 0.9960 0.0001
1.0000 -0.0000 1.0000 -0.0000
This is the toString() code used to make it work:
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;
}
And the main I used:
public static void main (String args[]){
Airfoil air = new Airfoil("1000");
System.out.println(air.toString());
}
Related
I'm just playing with Android Studio bitmaps and have created a dotted background for my application through iteration.
constant = 60;
int padding_X = (int) Math.floor((width % constant)/2f);
if (padding_X == 0) {
padding_X = (int) Math.floor(constant / 2);
}
int padding_Y = (int) Math.floor((height % constant)/2f);
if (padding_Y == 0) {
padding_Y = (int) Math.floor(constant/2);
}
System.out.println("padding X: "+padding_X);
System.out.println("padding Y: "+padding_Y);
int max_xn = Math.round((width-(padding_X*2)) / constant);
int max_yn = Math.round((height-(padding_Y*2)) / constant);
System.out.println("max xn: "+max_xn);
System.out.println("max yn: "+max_yn);
point_matrix = new int[max_xn+1][max_yn+1][2];
lens = new int[2];
for (int yn = 0; yn <= max_yn; yn++) {
int y = (int) (padding_Y + (yn*constant));
for (int xn = 0; xn <= max_xn; xn++) {
int x = (int) (padding_X + (xn*constant));
System.out.println("point # x: "+x+" y: "+y);
canvas.setPixel(x,y,Color.parseColor("#ffffff"));
point_matrix[xn][yn][0] = x;
point_matrix[xn][yn][1] = y;
}
}
runOnUiThread(() -> {
iv0.setImageBitmap(canvas);
});
lens[0] = max_xn+1;
lens[1] = max_yn+1;
I have also added each white pixel to a 3 dimensional array int[][][]. The array holds xn and yn for indexing the dots. Last array holds the coordinates onscreen. Example: {5, 1, {100,250}} 5 is the dots index on x axis, 1 is the index on y axis and 100 and 250 are coordinates on the bitmap.
I'm hoping to find a way for finding all dots on the 3 dim. array on a certain radius from the center.
A plan I had was iterating through all elements in the 3dim array and calculating the distance to the center with pythagoras theorem or something like that but that would be really inefficient seeing as this would have to be done multiple times.
The final plan is to have all of the dots to dissapear in a circular motion starting from the center. With a delay between each "radius interval".
Use trigonometric functions :)
static double i = 0;
static double pi = Math.PI;
static int q = 5; // half size of array
static double x;
static double y;
static double cx = 5; // offset center x
static double cy = 5; // offset center y
public static void main(String[] args) {
while (i < pi * 2) { // pi*2 is full angle of circle
x = Math.round (cx + Math.sin(i) * q);
y = Math.round (cy + Math.cos(i) * q);
System.out.print(String.format("X = %4f", x) + String.format("Y = %4f", y) + "\n");
i+=pi/180;
}
}
I was wondering if when you call color.HSBtoRGB if the hue value would be entered as a range of 0-255, 0-1, 0-360? I am inquiring because I am trying to convert an edge angle to a color but it is only giving me blue or purple? can anyone explain what I am doing?
public void sobelGrey(){
this.greyScale();
double edgex;
double edgey;
Picture pi = new Picture(this.getWidth(), this.getHeight());
Picture tou = new Picture(this.getWidth(), this.getHeight());
Pixel[][] Y = pi.getPixels2D();
Pixel[][] X = tou.getPixels2D();
Pixel[][] h = this.getPixels2D();
for (int y = 1; y< X.length-1; y++){
for(int x= 1; x<X[1].length-1; x++){
edgex =
h[y-1][x-1].getRed() * -1 +
h[y][x-1].getRed() * -2+
h[y+1][x-1].getRed() * -1+
h[y-1][x+1].getRed() * 1 +
h[y][x+1].getRed() * 2+
h[y+1][x+1].getRed() * 1;
Y[y][x].setRed((int)Math.abs(edgex/2));
Y[y][x].setGreen((int)Math.abs(edgex/2));
Y[y][x].setBlue((int)Math.abs(edgex/2));
}
}
for (int y = 1; y< X.length-1; y++){
for(int x= 1; x<X[1].length-1; x++){
edgex =
h[y-1][x-1].getRed() * -1 +
h[y-1][x].getRed() * -2+
h[y-1][x+1].getRed() * -1+
h[y+1][x-1].getRed() * 1 +
h[y+1][x].getRed() * 2+
h[y+1][x+1].getRed() * 1;
X[y][x].setRed((int)Math.abs(edgex/2));
X[y][x].setGreen((int)Math.abs(edgex/2));
X[y][x].setBlue((int)Math.abs(edgex/2));
}
}
for (int y = 1; y< X.length-1; y++){
for(int x= 1; x<X[1].length-1; x++){
int x1 = (int) Math.sqrt(Math.pow(X[y][x].getRed(), 2) + Math.pow(X[y][x].getGreen(), 2) + Math.pow(X[y][x].getBlue(), 2));
int y1 = (int) Math.sqrt(Math.pow(Y[y][x].getRed(), 2) + Math.pow(Y[y][x].getGreen(), 2) + Math.pow(Y[y][x].getBlue(), 2));
int hr = (int) (200/(2*Math.PI)*(Math.tanh(y1/ (x1+.000000000000001))));
int rgb = Color.HSBtoRGB(hr/255, hr, (int) Math.sqrt(Math.pow(x1, 2) + Math.pow(y1, 2)));
Color fixed = new Color(rgb&0xFF*7/10, (rgb>>8)&0xFF*80/255/10, (rgb>>16)&0xFF*4/10);
if( !(Math.sqrt(Math.pow(x1, 2) + Math.pow(y1, 2))< 40))
h[y][x].setColor(fixed);
else
h[y][x].setColor(Color.black);
}
}
pi.explore();
tou.explore();
explore();
}
i am using a computer science AP image processing from Eimacs, and using the swan
You declared hr (and the other variables) to be an int. Then in Color.HSBtoRGB(hr/255, ... you divide an int by an int. For all values of hr below 255, the result will be 0.
Probably it is sufficient to divide by 255.0 to force a floating point division.
As the title suggests, I'm working on a homework assignment where we are limited to using multi-dimensional arrays in order to create a program that finds two points nearest to each other in a three dimensional space. So far my code looks like this (hybridized from examples in my textbook and my own code):
package exercise7_7;
public class Exercise7_7 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Enter the number of points:");
int numberOfPoints = input.nextInt();
double[][] points = new double[numberOfPoints][3];
System.out.println("Enter " + numberOfPoints + " points:");
for (int i = 0; i < points.length; i++) {
points[i][0] = input.nextDouble();
points[i][1] = input.nextDouble();
points[i][2] = input.nextDouble();
}
int p1 = 0, p2 = 1, p3 = 2;
double shortestDistance = distance(points[p1][0] , points[p1][1] , points[p1][2] ,
points[p2][0] , points[p2][1] , points[p2][2]);
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
double distance = distance(points[i][0] , points[j][0] , points[j][1] , points[j][2] , points[i][2] , points[j][2]);
if (shortestDistance > distance) {
p1 = i;
p2 = j;
shortestDistance = distance;
}
}
}
System.out.println("The closest two points are " + "(" + points[p1][0] + "," + points[p1][1] +
and (" + points[p2][0] + "," );
}
public static double distance(
double x1, double y1, double z1, double x2, double y2, double z2) {
return Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)) + ((z2 - z1) * (z2 - z1)));
}
}
What I mostly need help with is figuring out just how to get these points compared. I don't think the way I tackled this problem was the best way to do it.
Thanks for the help guys. I'm running on 2 hours of sleep for 2 days now so please excuse any stupid questions or sloppy code.
******
I think I've got it:
package exercise7_7;
public class Exercise7_7 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Enter the number of points:");
int numberOfPoints = input.nextInt();
double[][] points = new double[numberOfPoints][3];
System.out.println("Enter " + numberOfPoints + " points:");
for (int i = 0; i < points.length; i++) {
points[i][0] = input.nextDouble();
points[i][1] = input.nextDouble();
points[i][2] = input.nextDouble();
}
int p1 = 0, p2 = 1;
double shortestDistance = distance(points[p1][0] , points[p1][1] , points[p1][2] ,
points[p2][0] , points[p2][1] , points[p2][2]);
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
double distance = distance(points[i][0] , points[j][0] , points[j][1] , points[j][2] , points[i][2] , points[j][2]);
if (shortestDistance > distance) {
p1 = i;
p2 = j;
shortestDistance = distance;
}
}
}
System.out.println("The closest two points are " + "(" + points[p1][0] + "," + points[p1][1] + "," + points[p1][2] +
") and (" + points[p2][0] + "," + points[p2][1] + "," + points[p2][2] + ")");
}
public static double distance(
double x1, double y1, double z1, double x2, double y2, double z2) {
return Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)) + ((z2 - z1) * (z2 - z1)));
}
}
Input is taken in, processed, and then outputs the two closest points. Just as a reference, when:
(-1,0,3),(-1,-1,-1),(4,1,1),(2,0.5,9),(3.5,1.5,3),(-1.5,4,2),(5.5,4,-0.5) are inputted, the outcome
seems to be (-1,0,3) and (4,1,1). Could someone confirm that for me.
If this isn't the way to follow up on my own question, I apologize. First day on these slopes and I'm still
learning the ropes.
Use a class to represent your points. This way to you have a distanceTo method that calculates and returns distance. Also you can have a toString method that prints out the point for display to the user. Taking your code rearranging yields this class:
public class ThreeDPoint {
final double x;
final double y;
final double z;
public ThreeDPoint(final double x, final double y, final double z) {
this.x = x;
this.y = y;
this.z = z;
}
public double distanceto(final ThreeDPoint other) {
final double dx = other.x - x;
final double dy = other.y - y;
final double dz = other.z - z;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
#Override
public String toString() {
return "{X=" + x + ",Y=" + y + ",Z=" + z + "}";
}
}
Now putting that together gives this, which is much more readable. I have removed the bit where you read points and used random numbers:
public static void main(String args[]) {
final ThreeDPoint[] points = new ThreeDPoint[5];
final Random random = new Random();
for (int i = 0; i < points.length; ++i) {
points[i] = new ThreeDPoint(random.nextInt(100), random.nextInt(100), random.nextInt(100));
}
//store min
double min = Double.POSITIVE_INFINITY;
int first = -1;
int last = -1;
for (int i = 0; i < points.length; ++i) {
for (int j = i + 1; j < points.length; ++j) {
final double d = points[i].distanceto(points[j]);
if (d < min) {
min = d;
first = i;
last = j;
}
}
}
System.out.println("The minimum distance is between point " + first + " and " + last + "(" + points[first] + " and " + points[last] + "). This distance is " + min + ".");
}
private static final class ThreeDPoint {
final double x;
final double y;
final double z;
public ThreeDPoint(final double x, final double y, final double z) {
this.x = x;
this.y = y;
this.z = z;
}
public double distanceto(final ThreeDPoint other) {
final double dx = other.x - x;
final double dy = other.y - y;
final double dz = other.z - z;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
#Override
public String toString() {
return "{X=" + x + ",Y=" + y + ",Z=" + z + "}";
}
}
I used perlin noise to generate a 2D height map. At first i tried some parameters manually and found a good combination of amplitude, persistence,... for my job.
Now that i'm developing the program, i added the feature for user to change the map parameters and make a new map for himself but now i see that for certain parameters (Mostly octaves and frequency) the values are not in the range i used to see. I thought that if a set Amplitude = 20, the values(heights) i get from it will be in e.g [0,20] or [-10,10] or [-20,20] ranges but now i see that Amplitude is not the only parameter that controls output range.
My question is: Is there an exact mathematical formula (a function of Amplitude, Octaves, Frequency and persistence) to compute the range or i should take a lot of samples (like 100,000) and check minimum and maximum values of them to guess the aproximate range?
Note: The following code is an implementation of perlin noise that one of stackoverflow guys worte it in C and i ported it to java.
PerlinNoiseParameters.java
public class PerlinNoiseParameters {
public double persistence;
public double frequency;
public double amplitude;
public int octaves;
public int randomseed;
public PerlinNoiseParameters(double persistence, double frequency, double amplitude, int octaves, int randomseed) {
this.ChangeParameters(persistence, frequency, amplitude, octaves, randomseed);
}
public void ChangeParameters(double persistence, double frequency, double amplitude, int octaves, int randomseed) {
this.persistence = persistence;
this.frequency = frequency;
this.amplitude = amplitude;
this.octaves = octaves;
this.randomseed = 2 + randomseed * randomseed;
}
}
PerlinNoiseGenerator.java
public class PerlinNoiseGenerator {
PerlinNoiseParameters parameters;
public PerlinNoiseGenerator() {
}
public PerlinNoiseGenerator(PerlinNoiseParameters parameters) {
this.parameters = parameters;
}
public void ChangeParameters(double persistence, double frequency, double amplitude, int octaves, int randomseed) {
parameters.ChangeParameters(persistence, frequency, amplitude, octaves, randomseed);
}
public void ChangeParameters(PerlinNoiseParameters newParams) {
parameters = newParams;
}
public double get(double x, double y) {
return parameters.amplitude * Total(x, y);
}
private double Total(double i, double j) {
double t = 0.0f;
double _amplitude = 1;
double freq = parameters.frequency;
for (int k = 0; k < parameters.octaves; k++) {
t += GetValue(j * freq + parameters.randomseed, i * freq + parameters.randomseed)
* _amplitude;
_amplitude *= parameters.persistence;
freq *= 2;
}
return t;
}
private double GetValue(double x, double y) {
int Xint = (int) x;
int Yint = (int) y;
double Xfrac = x - Xint;
double Yfrac = y - Yint;
double n01 = Noise(Xint - 1, Yint - 1);
double n02 = Noise(Xint + 1, Yint - 1);
double n03 = Noise(Xint - 1, Yint + 1);
double n04 = Noise(Xint + 1, Yint + 1);
double n05 = Noise(Xint - 1, Yint);
double n06 = Noise(Xint + 1, Yint);
double n07 = Noise(Xint, Yint - 1);
double n08 = Noise(Xint, Yint + 1);
double n09 = Noise(Xint, Yint);
double n12 = Noise(Xint + 2, Yint - 1);
double n14 = Noise(Xint + 2, Yint + 1);
double n16 = Noise(Xint + 2, Yint);
double n23 = Noise(Xint - 1, Yint + 2);
double n24 = Noise(Xint + 1, Yint + 2);
double n28 = Noise(Xint, Yint + 2);
double n34 = Noise(Xint + 2, Yint + 2);
double x0y0 = 0.0625 * (n01 + n02 + n03 + n04) + 0.1250
* (n05 + n06 + n07 + n08) + 0.2500 * n09;
double x1y0 = 0.0625 * (n07 + n12 + n08 + n14) + 0.1250
* (n09 + n16 + n02 + n04) + 0.2500 * n06;
double x0y1 = 0.0625 * (n05 + n06 + n23 + n24) + 0.1250
* (n03 + n04 + n09 + n28) + 0.2500 * n08;
double x1y1 = 0.0625 * (n09 + n16 + n28 + n34) + 0.1250
* (n08 + n14 + n06 + n24) + 0.2500 * n04;
double v1 = Interpolate(x0y0, x1y0, Xfrac);
double v2 = Interpolate(x0y1, x1y1, Xfrac);
double fin = Interpolate(v1, v2, Yfrac);
return fin;
}
private double Interpolate(double x, double y, double a) {
double negA = 1.0 - a;
double negASqr = negA * negA;
double fac1 = 3.0 * (negASqr) - 2.0 * (negASqr * negA);
double aSqr = a * a;
double fac2 = 3.0 * aSqr - 2.0 * (aSqr * a);
return x * fac1 + y * fac2;
}
private double Noise(int x, int y) {
int n = x + y * 57;
n = (n << 13) ^ n;
int t = (n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff;
return 1.0 - (double) t * 0.931322574615478515625e-9;
}
}
The range of a single perlin noise step is:
http://digitalfreepen.com/2017/06/20/range-perlin-noise.html
-sqrt(N/4), sqrt(N/4)
With N being the amount of dimensions. 2 in your case.
Octaves, persistence and amplitude add on top of that:
double range = 0.0;
double _amplitude = parameters.;
for (int k = 0; k < parameters.octaves; k++) {
range += sqrt(N/4) * _amplitude;
_amplitude *= parameters.persistence;
}
return range;
There might be some way to do this as a single mathematical expression. Involving pow(), but by brain fails me right now.
This is not a problem with octaves and frequency affecting amplitude, not directly at least. It is a problem with integer overflow. Because you introduce your random seed by adding it to the the x and y co-ordinates (which is unusual, I don't think this is the usual implimentation)
t += GetValue(j * freq + parameters.randomseed, i * freq + parameters.randomseed)* _amplitude;
And random seed could be huge (possibly the near full size of the int) because
this.randomseed = 2 + randomseed * randomseed;
So if you input large values for j and i you end up with the doubles that are passed through at GetValue(double x, double y) being larger than the maximum size of int, at that point when you call
int Xint = (int) x;
int Yint = (int) y;
Xint and YInt won't be anything like x and y (because x and y could be huge!) and so
double Xfrac = x - Xint;
double Yfrac = y - Yint;
could be much much larger that 1, allowing values not between -1 and 1 to be returned.
Using reasonable and small values my ranges using your code are between -1 and 1 (for amplitude 1)
As an asside, in java usually method names are methodName, not MethodName
If its useful please find annother java implimentation of perlin noise here:
http://mrl.nyu.edu/~perlin/noise/
I have a standalone Java application below that is:
Generating a random line
Applied to a 2D grid where each cell value is the distance along the line perpindicular to the line
Finds the rise/run and attempts to calculate the original linear equation from the grid
Applies new line to another grid and prints out the greatest difference compared to the first grid
I expected the two grids to have identical values. The gradient lines may be different since the lines can extend outside the area of the grid, but should be similar and in two cases identical.
So is the problem a poor understanding of math, a bug in my code or a misunderstanding of floating point values?
import java.awt.geom.Point2D;
import java.awt.geom.Line2D;
import java.util.Iterator;
import java.util.ArrayList;
public final class TestGradientLine {
private static int SIZE = 3;
public TestGradientLine() {
super();
}
//y = mx + b
//b = y - mx
//m is rise / run = gradient
//width and height of bounding box
//for a box 10x10 then width and height are 9,9
public static Line2D getGradientLine(double run, double rise, double width, double height, double x, double y) {
if (run == 0 && rise == 0) {
return new Line2D.Double(x, y, x + width, y + height);
}
//calculate hypotenuse
//check for a vertical line
if (run == 0) {
return new Line2D.Double(x, y, x, y + height);
}
//check for a horizontal line
if (rise == 0) {
return new Line2D.Double(x, y, x + width, y);
}
//calculate gradient
double m = rise / run;
Point2D start;
Point2D opposite;
if (m < 0) {
//lower left
start = new Point2D.Double(x, y + height);
opposite = new Point2D.Double(x + width, y);
} else {
//upper left
start = new Point2D.Double(x, y);
opposite = new Point2D.Double(x + width, y + height);
}
double b = start.getY() - (m * start.getX());
//now calculate another point along the slope
Point2D next = null;
if (m > 0) {
next = new Point2D.Double(start.getX() + Math.abs(run), start.getY() + Math.abs(rise));
} else {
if (rise < 0) {
next = new Point2D.Double(start.getX() + run, start.getY() + rise);
} else {
next = new Point2D.Double(start.getX() - run, start.getY() - rise);
}
}
final double actualWidth = width;
final double actualHeight = height;
final double a = Math.sqrt((actualWidth * actualWidth) + (actualHeight * actualHeight));
extendLine(start, next, a);
Line2D gradientLine = new Line2D.Double(start, next);
return gradientLine;
}
public static void extendLine(Point2D p0, Point2D p1, double toLength) {
final double oldLength = p0.distance(p1);
final double lengthFraction =
oldLength != 0.0 ? toLength / oldLength : 0.0;
p1.setLocation(p0.getX() + (p1.getX() - p0.getX()) * lengthFraction,
p0.getY() + (p1.getY() - p0.getY()) * lengthFraction);
}
public static Line2D generateRandomGradientLine(int width, int height) {
//so true means lower and false means upper
final boolean isLower = Math.random() > .5;
final Point2D start = new Point2D.Float(0, 0);
if (isLower) {
//change origin for lower left corner
start.setLocation(start.getX(), height - 1);
}
//radius of our circle
double radius = Math.sqrt(width * width + height * height);
//now we want a random theta
//x = r * cos(theta)
//y = r * sin(theta)
double theta = 0.0;
if (isLower) {
theta = Math.random() * (Math.PI / 2);
} else {
theta = Math.random() * (Math.PI / 2) + (Math.PI / 2);
}
int endX = (int)Math.round(radius * Math.sin(theta));
int endY = (int)Math.round(radius * Math.cos(theta)) * -1;
if (isLower) {
endY = endY + (height - 1);
}
final Point2D end = new Point2D.Float(endX, endY);
extendLine(start, end, radius);
return new Line2D.Float(start, end);
}
public static Point2D getNearestPointOnLine(Point2D end, Line2D line) {
final Point2D point = line.getP1();
final Point2D start = line.getP2();
double a = (end.getX() - point.getX()) * (start.getX() - point.getX()) + (end.getY() - point.getY()) * (start.getY() - point.getY());
double b = (end.getX() - start.getX()) * (point.getX() - start.getX()) + (end.getY() - start.getY()) * (point.getY() - start.getY());
final double x = point.getX() + ((start.getX() - point.getX()) * a)/(a + b);
final double y = point.getY() + ((start.getY() - point.getY()) * a)/(a + b);
final Point2D result = new Point2D.Double(x, y);
return result;
}
public static double length(double x0, double y0, double x1, double y1) {
final double dx = x1 - x0;
final double dy = y1 - y0;
return Math.sqrt(dx * dx + dy * dy);
}
public static void main(String[] args) {
final Line2D line = generateRandomGradientLine(SIZE, SIZE);
System.out.println("we're starting with line " + line.getP1() + " " + line.getP2());
double[][] region = new double[SIZE][SIZE];
//load up the region with data from our generated line
for (int x = 0; x < SIZE; x++) {
for (int y = 0; y < SIZE; y++) {
final Point2D point = new Point2D.Double(x, y);
final Point2D nearestPoint = getNearestPointOnLine(point, line);
if (nearestPoint == null) {
System.err.println("uh -oh!");
return;
}
final double distance = length(line.getP1().getX(),
line.getP1().getY(), nearestPoint.getX() + 1,
nearestPoint.getY() + 1);
region[x][y] = distance;
}
}
//now figure out what our line is from the region
double runTotal = 0;
double riseTotal = 0;
double runCount = 0;
double riseCount = 0;
for (int x = 0; x < SIZE; x++) {
for (int y = 0; y < SIZE; y++) {
if (x < SIZE - 1) {
runTotal += region[x + 1][y] - region[x][y];
runCount++;
}
if (y < SIZE - 1) {
riseTotal += region[x][y + 1] - region[x][y];
riseCount++;
}
}
}
double run = 0;
if (runCount > 0) {
run = runTotal / runCount;
}
double rise = 0;
if (riseCount > 0) {
rise = riseTotal / riseCount;
}
System.out.println("rise is " + rise + " run is " + run);
Line2D newLine = getGradientLine(run, rise, SIZE - 1, SIZE - 1, 0, 0);
System.out.println("ending with line " + newLine.getP1() + " " + newLine.getP2());
double worst = 0.0;
int worstX = 0;
int worstY = 0;
for (int x = 0; x < SIZE; x++) {
for (int y = 0; y < SIZE; y++) {
final Point2D point = new Point2D.Double(x, y);
final Point2D nearestPoint = getNearestPointOnLine(point, newLine);
if (nearestPoint == null) {
System.err.println("uh -oh!");
return;
}
final double distance = length(line.getP1().getX(),
line.getP1().getY(), nearestPoint.getX() + 1,
nearestPoint.getY() + 1);
final double diff = Math.abs(region[x][y] - distance);
if (diff > worst) {
worst = diff;
worstX = x;
worstY = y;
}
}
}
System.out.println("worst is " + worst + " x: " + worstX + " y: " + worstY);
}
}
I think I have fixed your program.
a) I took out the integer cast.
b) I removed all the 'x + 1' and 'x - 1' fudges you had used.
I think when dealing with floats and doubles, subtracting '1' from the end of a line is a No-No! What is 1 anyway? - it's ok to do this just before you plot it on the screen once it's an integer. But not while calculating! line length is a 'zero-based' quantity.
This version returns approx 4E-16 always.
import java.awt.geom.Point2D;
import java.awt.geom.Line2D;
import java.awt.geom.QuadCurve2D;
import java.util.Iterator;
import java.util.ArrayList;
public final class TestGradientLine {
private static int SIZE = 3;
public TestGradientLine() {
super();
}
//y = mx + b
//b = y - mx
//m is rise / run = gradient
//width and height of bounding box
//for a box 10x10 then width and height are 9,9
public static Line2D getGradientLine(double run, double rise, double width, double height, double x, double y) {
if (run == 0 && rise == 0) {
return new Line2D.Double(x, y, x + width, y + height);
}
//calculate hypotenuse
//check for a vertical line
if (run == 0) {
return new Line2D.Double(x, y, x, y + height);
}
//check for a horizontal line
if (rise == 0) {
return new Line2D.Double(x, y, x + width, y);
}
//calculate gradient
double m = rise / run;
Point2D start;
Point2D opposite;
if (m < 0) {
//lower left
start = new Point2D.Double(x, y + height);
opposite = new Point2D.Double(x + width, y);
} else {
//upper left
start = new Point2D.Double(x, y);
opposite = new Point2D.Double(x + width, y + height);
}
double b = start.getY() - (m * start.getX());
//now calculate another point along the slope
Point2D next = null;
if (m > 0) {
next = new Point2D.Double(start.getX() + Math.abs(run), start.getY() + Math.abs(rise));
} else {
if (rise < 0) {
next = new Point2D.Double(start.getX() + run, start.getY() + rise);
} else {
next = new Point2D.Double(start.getX() - run, start.getY() - rise);
}
}
final double actualWidth = width;
final double actualHeight = height;
final double a = Math.sqrt((actualWidth * actualWidth) + (actualHeight * actualHeight));
extendLine(start, next, a);
Line2D gradientLine = new Line2D.Double(start, next);
return gradientLine;
}
public static void extendLine(Point2D p0, Point2D p1, double toLength) {
final double oldLength = p0.distance(p1);
final double lengthFraction =
oldLength != 0.0 ? toLength / oldLength : 0.0;
p1.setLocation(p0.getX() + (p1.getX() - p0.getX()) * lengthFraction,
p0.getY() + (p1.getY() - p0.getY()) * lengthFraction);
}
public static Line2D generateRandomGradientLine(int width, int height) {
//so true means lower and false means upper
final boolean isLower = Math.random() > .5;
final Point2D start = new Point2D.Float(0, 0);
if (isLower) {
//change origin for lower left corner
start.setLocation(start.getX(), height );
}
//radius of our circle
double radius = Math.sqrt(width * width + height * height);
//now we want a random theta
//x = r * cos(theta)
//y = r * sin(theta)
double theta = 0.0;
if (isLower) {
theta = Math.random() * (Math.PI / 2);
} else {
theta = Math.random() * (Math.PI / 2) + (Math.PI / 2);
}
float endX = (float)(radius * Math.sin(theta));
float endY = (float)(radius * Math.cos(theta)) * -1;
if (isLower) {
endY = endY + (height );
}
final Point2D end = new Point2D.Float(endX, endY);
extendLine(start, end, radius);
return new Line2D.Float(start, end);
}
public static Point2D getNearestPointOnLine(Point2D end, Line2D line) {
final Point2D point = line.getP1();
final Point2D start = line.getP2();
double a = (end.getX() - point.getX()) * (start.getX() - point.getX()) + (end.getY() - point.getY()) * (start.getY() - point.getY());
double b = (end.getX() - start.getX()) * (point.getX() - start.getX()) + (end.getY() - start.getY()) * (point.getY() - start.getY());
final double x = point.getX() + ((start.getX() - point.getX()) * a)/(a+b);
final double y = point.getY() + ((start.getY() - point.getY()) * a)/(a+b);
final Point2D result = new Point2D.Double(x, y);
return result;
}
public static double length(double x0, double y0, double x1, double y1) {
final double dx = x1 - x0;
final double dy = y1 - y0;
return Math.sqrt(dx * dx + dy * dy);
}
public static void main(String[] args) {
final Line2D line = generateRandomGradientLine(SIZE, SIZE);
System.out.println("we're starting with line " + line.getP1() + " " + line.getP2());
double[][] region = new double[SIZE][SIZE];
//load up the region with data from our generated line
for (int x = 0; x < SIZE; x++) {
for (int y = 0; y < SIZE; y++) {
final Point2D point = new Point2D.Double(x, y);
final Point2D nearestPoint = getNearestPointOnLine(point, line);
if (nearestPoint == null) {
System.err.println("uh -oh!");
return;
}
final double distance = length(line.getP1().getX(),
line.getP1().getY(), nearestPoint.getX() ,
nearestPoint.getY() );
region[x][y] = distance;
}
}
//now figure out what our line is from the region
double runTotal = 0;
double riseTotal = 0;
double runCount = 0;
double riseCount = 0;
for (int x = 0; x < SIZE; x++) {
for (int y = 0; y < SIZE; y++) {
if (x < SIZE - 1) {
runTotal += region[x + 1][y] - region[x][y];
runCount++;
}
if (y < SIZE - 1) {
riseTotal += region[x][y + 1] - region[x][y];
riseCount++;
}
}
}
double run = 0;
if (runCount > 0) {
run = runTotal / runCount;
}
double rise = 0;
if (riseCount > 0) {
rise = riseTotal / riseCount;
}
System.out.println("rise is " + rise + " run is " + run);
Line2D newLine = getGradientLine(run, rise, SIZE, SIZE , 0, 0);
System.out.println("ending with line " + newLine.getP1() + " " + newLine.getP2());
double worst = 0.0;
int worstX = 0;
int worstY = 0;
for (int x = 0; x < SIZE; x++) {
for (int y = 0; y < SIZE; y++) {
final Point2D point = new Point2D.Double(x, y);
final Point2D nearestPoint = getNearestPointOnLine(point, newLine);
if (nearestPoint == null) {
System.err.println("uh -oh!");
return;
}
final double distance = length(line.getP1().getX(),
line.getP1().getY(), nearestPoint.getX() ,
nearestPoint.getY() );
final double diff = Math.abs(region[x][y] - distance);
if (diff > worst) {
worst = diff;
worstX = x;
worstY = y;
}
}
}
System.out.println("worst is " + worst + " x: " + worstX + " y: " + worstY);
}
}
why do you multiply by -1 at the end of this line?
int endY = (int)Math.round(radius * Math.cos(theta)) * -1;
this means that endY is always negative except radius is below 0. (cosinus always returns positive value)
is this intended or am i getting something wrong?
regards
You probably misunderstand float and/or double. This is a common problem with any language that implements the ieee spec for floats and doubles, which Java, C, C++ and just about every other language does.
Essentially
double val = 0;
for(int i=0;i<10;i++) {
val+=0.1;
System.out.println(val);
}
results in
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
And sometimes even worse. Either use BigDecimal, which alleviates a lot of the problem, or use integers.