Best range finder

It works great the first 45cm then slowly loses accuracy. Here are some of the sample codes that I have tried

#include <DistanceGP2Y0A21YK.h>

DistanceGP2Y0A21YK Dist;
int distance;

void setup()
{
  Serial.begin(9600);
  Dist.begin(A0);
}

void loop()
{
  distance = Dist.getDistanceCentimeter();
  Serial.print("\nDistance in centimers: ");
  Serial.print(distance);  
  delay(500); //make it readable
}
int i;
int val;
int redpin=0;
void setup() {
    pinMode(redpin,OUTPUT);
    Serial.begin(9600);
}
void loop() {
    i=analogRead(redpin);
    val=(6762/(i-9))-4;
    Serial.println(val);
}

I have also just tried reading the raw analog values that come out using a ruler, but as the distance stays fixed the value will go from 250 to 230 to 255 and all over.