views:

84

answers:

5

In PHP if you go above INT_MAX it will cast it as a float, allowing very high numbers to be formed (that are non-decimal as well), is this possible to do in C++ or are the way they store floating point/double precision numbers different?

The reason why is I am wishing to benchmark large factorials, but something such as 80! is way too large for an unsigned integer..

+1  A: 

The language will not make the switch for you, but has the datatypes float and double, which are usually 32 bit and 64 bit IEEE floats, respectively.

A 64 bit double has enough range for 80!, but doesn't have enough precision to represent it exactly. The language doesn't have anything built in that can do that: you would need to use a big integer library, for example GMP.

Steve Jessop
+1  A: 

Use one of bigint libraries, which allow you to create arbitrary precission ints in cost of performance. Or you have to write your own class to emulate PHPs hybrid float-int functionality

Something like this

class IntFloat {
   union {
      float fval;
      int ival;
    } val;
    bool foatUsed;

    public:
      setVal(float val)
      {
        this->val.fval = val;
        floatUsed = true;
      }

      setVal(int val)
      {
        this->val.ival = val;
        floatUsed = false;
      }

       //additional code for getters, setters, operators etc
 }

However what PHP does isn't worthy of imitation.

You can find list of big int libraries on wikipedia

PS:

"or are the way they store floating point/double precision numbers different?"

Yes it is different. C++ stores them straightly in target machine format, whle PHP uses intermediate representation (or bytecode, or in case of PHP opcode). Thus PHP converts number to machine format under the hood.

doc
+1  A: 

try using the GMP library or there are several other Big Integer libraries provided for C++. You may also use string manipulation to calculate large factorials. Click here for the algorithm and its explanation.

vaibhav
+1  A: 

C++ doesn't have such kind of "automatic casting" facilities, even if you could build a class that mimics such behavior by having an int and a float (a double would be even better, IIRC it lets you get up to 170!) private fields and some operator overloading black magic.

Anyhow, going from integers to fp you're going to lose precision, so, even if you can reach higher numbers, you aren't going to represent them exactly. Actually, if you're going in fp fields with factorials usually you could just use the Stirling's approximation (but I understand that in this case it do not apply, since it's a benchmark).

If you want to get to arbitrarily big factorials without losing precision, the usual solution is to use some bigint library; you can find several of them easily with Google.

Matteo Italia
A: 

You can use __float128 (long double) if precision is enough and you compiler supports it.

ssianky