OpenCL producing incorrect calculations
I've been trying to use openCL to do some calculations, but the results are incorrect.
I input three float3's that look like this:
[300000,0,0]
[300000,300000,0]
[300000,300000,300000]
into this kernel:
__kernel void gravitate(__global const float3 *position,__global const float3 *momentum,__global const float3 *mass,__global float3 *newPosition,__global float3 *newMomentum,unsigned int numBodies,unsigned int seconds)
{
int gid=get_global_id(0);
newPosition[gid]=position[gid]*2;
newMomentum[gid]=momentum[gid]*2;
}
I was originally trying to simulate the gravitational interaction of a group of bodies which is why the kernel looks like that.
For ouput I get:
[600000.0,0.0,0.0]
[x,600000.0,0.0]
[600000.0,x,600000.0]
Where x is a value that ranges from NaN to between 0 and 10^-44 and is different every time the kernel is run. Both newPosition and newMomentum have the same incorrect output pattern.
The python code that I'm using looks like this:
def __init__(self):
self.context=cl.create_some_context()
self.queue=cl.CommandQueue(self.context)
f=open("gravitate.cl")
self.program=cl.Program(self.context,f.read()).build()
def simulate(self,seconds):
bodyPosition=[]
bodyMomentum=[]
bodyMass=[]
for body in self.objects:
bodyPosition+=[body.position.x,body.position.y,body.position.z]
bodyMomentum+=[body.momentum.x,body.momentum.y,body.momentum.z]
bodyMass+=[body.m开发者_如何学运维ass]
bodyPosition=numpy.array(bodyPosition).astype(numpy.float32)
bodyMomentum=numpy.array(bodyMomentum).astype(numpy.float32)
bodyMass=numpy.array(bodyMass).astype(numpy.float32)
bodyPositionCl=cl.Buffer(self.context,cl.mem_flags.READ_ONLY|cl.mem_flags.COPY_HOST_PTR,hostbuf=bodyPosition)
bodyMomentumCl=cl.Buffer(self.context,cl.mem_flags.READ_ONLY|cl.mem_flags.COPY_HOST_PTR,hostbuf=bodyMomentum)
bodyMassCl=cl.Buffer(self.context,cl.mem_flags.READ_ONLY|cl.mem_flags.COPY_HOST_PTR,hostbuf=bodyMass)
newBodyPosition=numpy.zeros(len(self.objects)*3).astype(numpy.float32)
newBodyMomentum=numpy.zeros(len(self.objects)*3).astype(numpy.float32)
newBodyPositionCl=cl.Buffer(self.context,cl.mem_flags.WRITE_ONLY,newBodyPosition.nbytes)
newBodyMomentumCl=cl.Buffer(self.context,cl.mem_flags.WRITE_ONLY,newBodyMomentum.nbytes)
self.program.gravitate(self.queue,(3,),None,bodyPositionCl,bodyMomentumCl,bodyMassCl,newBodyPositionCl,newBodyMomentumCl,numpy.uint32(len(self.objects)),numpy.uint32(seconds))
cl.enqueue_read_buffer(self.queue,newBodyPositionCl,newBodyPosition).wait()
cl.enqueue_read_buffer(self.queue,newBodyMomentumCl,newBodyMomentum).wait()
float3 are 16-byte aligned. See OpenCL 1.1 spec, 6.1.5.
精彩评论