Hobbs2000 - 1 year ago 50

Java Question

I currently have a program that makes a fractal tree. However, I would like to use the golden ratio in my fractal tree to get more interesting designs. I do not know exactly how to implement it with coordinates, especially with java since (0,0) is in the top left, which makes things a bit more confusing. You may ignore the parameters

`adder`

`length`

`public void paintComponent(Graphics g)`

{

g.setColor(Color.RED);

draw(g, order, topX, topY,90,20, 200.00);

}

public void draw(Graphics g, int order, int x1, int y1, double angle, int adder, double length)

{

int x2, y2, x3, y3;

double newAngle = Math.toRadians(angle);

if (order == 1)

{

return;

}

else

{

x2 = (x1 - (int)Math.round(Math.cos(newAngle) * order * 10));

y2 = (y1 - (int)Math.round(Math.sin(newAngle) * order * 10));

g.drawLine(x1, y1, x2, y2);

draw(g, order-1, x2, y2, angle+30, adder+2, length+20);

draw(g, order-1, x2, y2, angle-30, adder+2, length+20);

}

}

This is what the current output is at an order of 10.

Answer

One approach to integrating the golden ratio into your code is to use it in the computation of branch length. Here, though you have a `length`

parameter, it's unused. Instead, the length is computed as `order * 10`

such that the trunk is 100 long, and by the time order reaches 2, the leaves are 20 long.

If you use the length parameter, and recurse such that each successive branch order is 0.618034 the length of the ancestor one, you make a tree that has a longer trunk and core branches, and converges to a kind of broccoli-like detail at the leaves:

The other parameter you have control over is the angle, which you've set to 30 degrees. Below, I've converted your code over to Processing (it's basically Java, and easy to use for these kinds of things). You can paste this into http://www.openprocessing.org/sketch/create and run it in your browser to play around. Look how replacing the angle of 30 with uniform random number between 20 and 40 changes the tree. Keep clicking *run* to see different trees.

```
void setup()
{
size(1000,1000);
smooth();
stroke(0);
frameRate(30);
}
void go(int order, int x1, int y1, float angle, int adder, int length)
{
int x2, y2, x3, y3;
double newAngle = angle * PI / 180;
if (order == 1)
{
return;
}
else
{
x2 = (x1 - round(cos(newAngle) * length));
y2 = (y1 - round(sin(newAngle) * length));
line(x1, y1, x2, y2);
go(order-1, x2, y2, angle+random(20,40), adder+2, 0.618034 * length);
go(order-1, x2, y2, angle-random(20,40), adder+2, 0.618034 * length);
}
}
void draw()
{
stroke(255, 0, 0);
strokeWeight(1);
go(10, 500, 999, 90, 20, 100);
exit();
}
```

Here's an interesting, slightly off-balance tree generated by the above code:

Source (Stackoverflow)