Skip to main content
added 6 characters in body
Source Link
Hastur
  • 277
  • 4
  • 10

C/C++ cmath

C/C++

C/C++ cmath

Source Link
Hastur
  • 277
  • 4
  • 10

C/C++

The curse of the numbers below 473 and above 474...

#include <iostream>
#include <cmath>
#include <stdlib.h>

const int MaxA=5;
const int MaxB=5;
int A[] = {469,  470 , 471 ,472, 473};
int B[] = {474,  475 , 476 ,477, 478};

int Check_And_Calculate(int d, int c1,int c2){
 // It does a check on c1 and c2 and return the value of `-cubic root of c1^3` // 
 if (c1>c2) std::cerr << "# "<< c1 << " is **BIGGER** then " << c2 << std::endl;
     else   std::cerr << "# "<< c1 << " is NOT bigger then " << c2 << std::endl;
 return  -cbrt(c1*c1*c1)   ;
}

int main()
{
  int a=2, b=2;
  srand48(time(NULL));               // Random seed: Randomize the seed...
  int ValueA=A[int(MaxA*drand48())]; // It Extracts one random element from A
  int ValueB=B[int(MaxB*drand48())]; // It Extracts one random element from B

  a=a+Check_And_Calculate(a,ValueA,ValueB)+ValueB;  // It adds B subtracts A
  b=b+Check_And_Calculate(b,ValueB,ValueA)+ValueA;  // It adds A subtracts B

  std::cout << "2+2=" << a+b << "\n";
  return 0 ;
}

Output

# 473 is NOT bigger then 476
# 476 is **BIGGER** then 473 
2+2=5

Explanation

We could say that the A group are the good ones (at least this time) and the B ones are the Bad Guys. (They have a lot of friend! see below).
For some numbers we can observe the following behaviour for the cubic square root function, cbrt(x) and for the power one pow(x,1./3.)
3^3=27
pow(27.,1./3/)= 3.0000000000000004
15^3=3375
pow(3375.,1./3/)=14.999999999999998

When it is returned by an integer function it is made an automatic cast:
3.0000000000000004 becomes 3
14.999999999999998 becomes 14
So at the end it seems it was not a curse but only a problem of bad casting...

Notes:

The comparison in the function is needed (or some other code at least) else when it is compiled with -O1,-O2,-O3 option the code is substituted and the effect disappears.

The Wild Bunch
int MaxB=147;
B[]={15,27,30,37,54,60,67,71,74,108,117,119,120,134,139,142,148,161,191,205,216,221,225,229,234,237,238,239,240,253,268,278,284,296,315,322,382,407,410,417,431,432,439,441,442,443,445,449,450,458,465,468,474,475,476,477,478,480,481,487,501,505,506,527,536,551,556,563,567,568,592,593,630,641,644,743,751,764,775,791,801,814,820,829,834,857,861,862,864,867,878,879,882,884,886,890,898,900,903,905,907,915,916,923,925,927,929,930,936,947,948,950,952,954,955,956,957,960,962,967,971,974,975,983,1002,1010,1012,1017,1021,1027,1031,1054,1072,1102,1112,1126,1133,1134,1136,1181,1184,1186,1213,1249,1260,1279,1282}