-1

I have the following code:

float test = 1/(10^(15));
std::cout << "test: " << test << std::endl;

But I get "test: 0" as the value. I want "test: 0.000000000000001".

How do I achieve this?

jotik
  • 17,044
  • 13
  • 58
  • 123
daemoner119
  • 113
  • 1
  • 9
  • 2
    You might want to try double instead of float http://stackoverflow.com/questions/28045787/how-many-decimal-places-does-the-primitive-float-and-double-support – SnoozeTime Jun 22 '16 at 01:54
  • 6
    `1/(10^(15))` -- That `^` doesn't do what you think it does. – PaulMcKenzie Jun 22 '16 at 01:55
  • @PaulMcKenzie probably because the site suggests "c" as a tag even when you wrote and tagged c++ already – M.M Jun 22 '16 at 02:02
  • 2
    @SnoozeTime: that's not the issue... keep in mind that the intended exponents are magnitude `15` - well within the -128..127 range supported by `float` - and while the number's not exactly representable, the 23 bits in the `float` will do a fair job. – Tony Delroy Jun 22 '16 at 02:11
  • @chema989 no, 1e15 is a `double`. There's no [integer literal](http://en.cppreference.com/w/cpp/language/integer_literal) format with an `e` in the middle. http://en.cppreference.com/w/cpp/language/floating_literal – phuclv Jun 22 '16 at 02:33
  • @LưuVĩnhPhúc, you are right. – chema989 Jun 22 '16 at 02:40

1 Answers1

8

There are multiple problems here.

10 ^ 15

It looks like you expect "^" to be the exponent operator, that is ten raised to the 15th power.

It is not. In C and C++, "^" is a bitwise exclusive-or operator.

The second problem is that all values in the expression are integer values. This means that (1/(10^15)) is computed as follows:

1) 10^15=5, remember that ^ is really a bitwise exclusive-or operator.

2) 1/5=0, because these are integer values, this is integer division, which is why you get the value of 0.

The best way to fix this is use scientific notation:

float test = 1/(1e15);
std::cout << "test: " << test << std::endl;

The scientific notation serves two purposes simultaneously: one, you get the right value, and two, this is automatically a floating point value, so the division is carried out as a floating point division.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148