码迷,mamicode.com
首页 > 其他好文 > 详细

cuda编程学习4——Julia

时间:2015-12-14 19:05:02      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

书上的例子编译会有错误,修改一下行即可。

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

/*
============================================================================
Name : Julia-CUDA.cu
Author : can
Version :
Copyright : Your copyright notice
Description : CUDA compute reciprocals
============================================================================
*/
#include<iostream>
using namespace std;
#include"cpu_bitmap.h"
#define DIM 100
struct cuComplex
{
float r,i;
__device__ cuComplex(float a,float b):r(a),i(b)
{}
__device__ float magnitude2(void)
{
return r*r+i*i;
}
__device__ cuComplex operator*(const cuComplex& a)
{
return cuComplex(r*a.r-i*a.i,r*a.i+i*a.r);
}
__device__ cuComplex operator+(const cuComplex& a)
{
return cuComplex(a.r+r,i+a.i);
}
};
__device__ 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(i=0;i<200;i++)
{
a=a*a+c;
if(a.magnitude2()>1000)
return 0;
}
return 1;
}
__global__ void kernel(unsigned char *ptr)
{
int x=blockIdx.x;
int y=blockIdx.y;
int offset=x+y*gridDim.x;//gridDim代表线程格的尺寸,gridDim.x代表线程格的x尺寸
int juliaValue=julia(x,y);//对位图中的每一个点进行计算判断是否属于Julia集
ptr[offset*4+0]=255*juliaValue;
ptr[offset*4+1]=0;
ptr[offset*4+2]=0;
ptr[offset*4+3]=255;
}
static void CheckCudaErrorAux (const char *file, unsigned line, const char *statement, cudaError_t err)
{
if (err == cudaSuccess)
return;
std::cerr << statement<<" returned " << cudaGetErrorString(err) << "("<<err<< ") at "<<file<<":"<<line << std::endl;
exit (1);
}
#define CUDA_CHECK_RETURN(value) CheckCudaErrorAux(__FILE__,__LINE__, #value, value)
int main(void)
{
CPUBitmap bitmap(DIM,DIM);
unsigned char*dev_bitmap;
CUDA_CHECK_RETURN(cudaMalloc((void**)&dev_bitmap,bitmap.image_size()));
dim3 grid(DIM,DIM);//block数量
kernel<<<grid,1>>>(dev_bitmap);
CUDA_CHECK_RETURN(cudaMemcpy(bitmap.get_ptr(),dev_bitmap,bitmap.image_size(),cudaMemcpyDeviceToHost));
bitmap.display_and_exit();
CUDA_CHECK_RETURN(cudaFree(dev_bitmap));
}

cuda编程学习4——Julia

标签:

原文地址:http://www.cnblogs.com/shrimp-can/p/5045902.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!