How can I launch particles from a random position?

Hello, I have been trying to launch particles from random positions, using G4Uniformrandom (), and / or using the example B1 that GEANT4 brings, but so far I have not succeeded, have you ever done this type of sequence? Also, the variable G4Uniformrandom () can be bounded, because as far as it goes, it only gives you values ​​of [0,1].

This is one of the many ways I’ve tried:

G4double R = - 8. + 5G4UniformRand() * (16.-8.);
G4double phi = G4UniformRand() * 2 * 3.1416;
G4double theta = G4UniformRand() * 3.1416;
G4double RandomX = R
cos(theta) * sin(phi);
G4double RandomY = R*sin(theta)*std:: sin(phi);

fParticleGun->SetParticlePosition(G4ThreeVector(RandomXm,RandomYm,10*m));

-.,.-,-
I have also tried it as follows:

G4int RandomX = (-8. + 3.*G4UniformRand()*7. + 4.);
G4cout<<"Valor X: "<<RandomX<<G4endl;
G4int RandomY = -5. + 3.G4UniformRand()-3. + 10.;
G4cout<<"Valor Y: "<<RandomY<<G4endl;

fParticleGun->SetParticlePosition(G4ThreeVector(RandomXm,RandomYm,10*m));

I want to generate random numbers in X [-8.8] and Y [-4.4]. I would greatly appreciate your help, I’ve been with this for two weeks :frowning:

Thank you very much!

Hi, after “SetParticlePosition”, you have to “GeneratePrimaryVertex”

See a similar code below
G4double x0 = 0cm, y0 = 0cm, z0 = -3cm;
G4double dx0 = 1.2
cm, dy0 = 0.6cm, dz0 = 0.5cm;
x0 += dx0*(G4UniformRand()-0.5);
y0 += dy0*(G4UniformRand()-0.5);
z0 += dz0*(G4UniformRand()-0.5);
fParticleGun->SetParticlePosition(G4ThreeVector(x0,y0,z0));
fParticleGun->GeneratePrimaryVertex(anEvent);