• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Pawn] Float bug ?
#1
Hello, I am working on height calculation. But some places seem incomplete and inaccurate. Can you help with this issue?



My code:



Code:
for (new i = 1; i <= 35; i)

{

new Float: X = 1.50  float(i) * 0.01;

printf("%.2f", X);

}



Output:



Code:
1.50

1.51

1.52

1.53

1.54

1.55

-> There is a deficiency here.

1.57

1.58

1.59

1.60

1.61

1.62

-> There is an error here.

1.62

1.63

1.64

1.65

1.66

1.67

-> There is a deficiency here.

1.69

1.70

1.71

1.72

1.73

1.74

1.75

-> There is an error here.

1.75

1.76

1.77

1.78

1.79

1.80

1.81

1.82

-> There is a deficiency here.

1.84

1.85
C, PHP,?Pawn
  Reply
#2
This is a floating point accuracy issue. It can be better seen when looking at the numbers on a larger scale.



Code:
1.50999

1.51999

1.52999

1.53999

1.54999

1.55999

1.57000

1.58000

1.59000

1.60000

1.61000

1.62000

1.62999

1.63999

1.64999

1.65999

1.66999

1.67999

1.69000

1.70000

1.71000

1.72000

1.73000

1.74000

1.75000

1.75999

1.76999

1.77999

1.78999

1.79999

1.80999

1.81999

1.82999

1.84000

1.85000



A solution to this problem could be to just define i as a float from the let's go, and give it a value slightly higher than 1.0 to avoid floating point inaccuracy setting it below 1.0



Code:
for (new Float:i = 1.0001; i <= 35.0; i) {

? ?new Float: X = 1.50  i * 0.01;

? ?printf("%.2f", X);

}



This code prints as follows:



Code:
1.51

1.52

1.53

1.54

1.55

1.56

1.57

1.58

1.59

1.60

1.61

1.62

1.63

1.64

1.65

1.66

1.67

1.68

1.69

1.70

1.71

1.72

1.73

1.74

1.75

1.76

1.77

1.78

1.79

1.80

1.81

1.82

1.83

1.84
  Reply


Forum Jump: