Help with find pitch code

Hello I’m using this function to find the pitch of sample i drop in my instrument but it seems not very accurate, is there any way to improve it? Thanks in advance for any help!

function setRootkey(sample)
    local zone = this.parent:getZone(1)
    local pitch, voiced = sample:getPitch(0, -1)
    if pitch and voiced then
        local rootkey, detune = math.modf(pitch)
        if detune >= 0.5 then
            rootkey = rootkey + 1
            detune = detune - 1
        end
        detune = math.floor((detune * 100) + 0.5)
        print(pitch, voiced, rootkey, detune)
        zone:setParameter("SampleOsc.Rootkey", rootkey)
        zone:setParameter("SampleOsc.Tune", detune)
    end
end```