您的位置:首页 > 其它

Julia on CPU

2013-11-14 03:51 218 查看
最近开始学习CUDA,感触良多。看书过程中发现Julia这个图形非常漂亮,照着书自己敲了一遍,发现其中运用了许多早已忘记的数学知识,于是赶紧恶补。

最终效果图:



/*

=========================编译环境=========================

系统: Win7 sp1 32位

CPU: AMD 黑盒5000+ oc到2.7GHz

内存: DDR2 800

显卡: ASUS GTX550Ti

环境: CUDA 5.5 + VisualStudio 2012 Ultimate update3

=========================================================

*/

以下为CPU执行的代码:

#include "common\cpu_bitmap.h"
#include "common\cpu_anim.h"

#define DIM 1000

struct cuComplex
{
float r;
float i;

cuComplex(float a, float b) : r(a), i(b)
{
}

// 复数乘法
// z1 = (r + i) z2 = (a.r + a.i)
// z1 * z2 = (r * a.r - i * a.i) + (r * a.i + i * a.r);
cuComplex operator* (const cuComplex &a)
{
return cuComplex(r * a.r - i * a.i, i * a.r + r * a.i);
}

// 复数加法
// z1 = (r + i) z2 = (a.r + a.i)
// z1 + z2 = (r + a.r) + (i + a.i)
cuComplex operator+ (const cuComplex &a)
{
return cuComplex(r + a.r, i + a.i);
}

// 复数的模
// 模∣z∣=√(a^2+b^2) (1)∣z∣≧0 (2)复数模的平方等于这个复数与它的共轭复数的积。
float magnitude2()
{
return r * r + i * i;
}
};

int julia(int x, int y)
{
const float scale = 1.5;
float jx = scale * (float)(DIM / 2 - x) / (DIM / 2);
float jy = scale * (float)(DIM / 2 - y) / (DIM / 2);

cuComplex c(-0.8, 0.156);		// 复数
cuComplex a(jx, jy);			// 实数

int i = 0;
for (int i = 0; i < 200; i++)
{
a = a * a + c;
if (a.magnitude2() > 1000)
return 0;
}
return 1;
}

void kernel(unsigned char *ptr)
{
for (int y = 0; y < DIM; y++)
{
for (int x = 0; x < DIM; x++)
{
int offset = x + y * DIM;
int juliaValue = julia(x, y);
// 每个颜色用4个字节表示,并给每个字节赋值
ptr[offset * 4 + 0] = 255 * juliaValue;			        // 确定图像的颜色的Red分量
ptr[offset * 4 + 1] = 0;					// 确定图像的颜色的Green分量
ptr[offset * 4 + 2] = 0;					// 确定图像的颜色的Blue分量
ptr[offset * 4 + 3] = 255;
}
}
}

int main()
{
CPUBitmap bitmap(DIM, DIM);
unsigned char *ptr = bitmap.get_ptr();

kernel(ptr);
bitmap.display_and_exit();
}
注:需要在项目属性中指定lib文件夹
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: