用Layman的话来说,分形是在计算和数学交织在一起时形成的美丽模式。为了获得一些技术性知识,它们本质上是递归的,因此当查看给定分形的某个子集时,似乎会出现类似的模式。
在本文中,生成了一种新型的分形图案,如下所示:
方法:
- 递归转到分形树的末端分支。
- 当分支的长度达到我们的阈值时,画出该特定分支并退出函数。
- 为了使颜色在几次迭代中保持相似,我们使用类型转换,因为((colorVal%15000)/ 1000 + 1)会给出相同值的光谱,即相同颜色在迭代前进行上千次。
下面是上述方法的实现:
// C++ code to Create a Butterfly
// themed Fractal using Graphics
#include
#include
#include
#define Y 1080
#define X 1920
// c is defined as the angle between each
// iterative lines, changing this would result
// in different and interesting patterns.
#define c 5 * M_PI / 7
// colorVal is used to provide different colors
// for each iterating point/line in the cycle.
int colorVal = 0;
// The core function in the program which is
// recursive in nature and terminates when the
// line size is less than 0.1 pixels.
int Pyt_Tree(float x, float y, float r, float ang)
{
// Max iteration condition so as to increase
// the accuracy of the fractal pattern.
// The closer it is to zero the higher the
// details but would cost more processing time.
if (r < 0.1) {
// combination of type casting and iteration
// so as to provide a Greatest Integer Function
// sort of manipulation for the color input.
setcolor((colorVal++ % 15000) / 1000 + 1);
// Conversion of the parametric coordinates
// of the points to the Argand coordinates
// while displaying them.
line(x, y, x - r * sin(ang), y - r * cos(ang));
return 0;
}
float r_n;
if (c > M_PI / 4) {
r_n = sin(c);
}
else {
r_n = cos(c);
}
// Recursive calling of the Pyt_Tree() function
// to get towards the end of the branch of the
// fractal tree.
Pyt_Tree(x - r * sin(ang), y - r * cos(ang),
r / (2 * r_n), (ang + c));
Pyt_Tree(x - r * sin(ang), y - r * cos(ang),
r / (2 * r_n), (ang - c));
return 0;
}
// Driver code
int main()
{
initwindow(X, Y);
Pyt_Tree(X / 2, Y, Y * 0.9, 0);
getch();
closegraph();
return 0;
}
输出:
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。