Advertisement
Kitomas

i32_error.c

Aug 24th, 2023
926
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.20 KB | None | 0 0
  1. //this will show that that conversion error for i32 and f32 is 64 and ~2.98023224e-8 respectively
  2. //(0.0000000298023223876953125 in normal notation, or about 3 ten millionths of a percent)
  3.  
  4. #define RANGE 100000000
  5.  
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <time.h>
  9. #include <stdint.h>
  10.  
  11. int get_random_i32(){
  12.     union {
  13.       struct {
  14.           uint16_t l;
  15.           uint16_t h;
  16.       };
  17.       int32_t i;
  18.     } output;
  19.     output.l=rand();
  20.     output.h=rand();
  21.     return output.i;
  22. }
  23.  
  24. //multiplying by inv32 is equivalent to dividing by 0x7fffffff
  25. const float inv32=1.0f/0x7fffffff;
  26. int32_t convert_from_and_to(int32_t input){
  27.     float from=(float)input*inv32;
  28.     return from*2147483647; //to
  29. }
  30.  
  31. int main(){
  32.     time_t t;
  33.     srand((unsigned)time(&t));
  34.    
  35.     int32_t mn=0,mx=0;
  36.     for(int i=0; i<RANGE; ++i){
  37.         int32_t src=get_random_i32();
  38.         int32_t dst=convert_from_and_to(src);
  39.         int32_t dif=dst-src;
  40.         if(dif<mn) mn=dif;
  41.         if(dif>mx) mx=dif;
  42.         //printf("%11i -> %11i (%i)\n",src,dst, dif);
  43.     }
  44.     //given enough RANGE, this should end up being -64 and 64 respectively
  45.     printf("min=%i, max=%i\n",mn,mx);
  46.    
  47.     return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement