I have a simple program that generates a position within a part. It works for the most part. Except for a few times when it just randomly generates a position way outside the part (20-5 studs)

Here’s the code.

local base = workspace.Base
local pos = Vector3.new(rand:NextNumber(-base.Size.X/2, base.Size.X/2), base.Position.Y, rand:NextNumber(-base.Size.Z/2,base.Size.Z/2))
local cf = CFrame.new(pos)

I am not the best with math, so I don’t know why it does that.

My first guess is that you have only factored in the base’s size, and forgot about its position:

local base = workspace.Base
local pos = base.Position + Vector3.new(
rand:NextNumber(-base.Size.X/2, base.Size.X/2),
0,
rand:NextNumber(-base.Size.Z/2, base.Size.Z/2)
)
local cf = CFrame.new(pos)

My second guess is that the way you are evaluating whether the position is outside of the part is faulty. For example, you might be cloning a model at position cf, but the model is sticking out a bit too much, or it might be assymmetrical or unanchored, and it leads to the conclusion that the model is in the wrong position.
Other than that, I don’t really see any problems with the snippet you’ve shown.

I put that in and all of a sudden the position jumped up way above. I know for a fact it’s not the part being generated at CF.

Instead, what I did was I did this:

local base = workspace.Base
local pos = Vector3.new(rand:NextNumber(-base.Size.X/3 + base.Position.X, base.Size.X/3),
base.Position.Y,
rand:NextNumber(-base.Size.Z/3,base.Size.Z/3) + base.Position.Z)
local cf = CFrame.new(pos)