infinite division problem

The purpose of this code is to add 1 + 1/2 + 1/4 + 1/8 + 1/16 ..... but the output is always 1 instead of going 1 , 1.5 , 1.75 ...... i know that the math is right so that's not the problem but there something wrong with how the code is doing it. it would be great if you could find a fix for this.

More Info

the math is based off the idea that if you add 1 + 1/2 + 1/4 + 1/8 + 1/16 ..... you will have to do it an infinite amount of times before you reach 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// ConsoleApplication3.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;


int main()
{
	double x = 0;
	double y = 1;
	do
	{
		x += y;
		y /= 2;
		cout << std::fixed << std::setprecision(100) << x << endl;
	} while (x < 3);

	return 0;
}
Last edited on
that's because you're doing it wrong.
You want x to be the output, right?
and y to count the denominator, right?

if so, your math is broken.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <iomanip>
using namespace std;


int main()
{
	double x = 0;
	double y = 1;
	do
	{
		x += y;
		y /= 2;
		cout << std::fixed << std::setprecision(50) << x << endl;
	}while (x < 200);
	
	return 0;
}
Wow that was fast, it seems to be working (i can see it in the 1.9's for a few mili seconds) but its reaching 2. that's mathematically impossible, is it rounding up. If so how do i change that.
you can't
it's the limit of computers and floating point datatypes.
you can only be accurate up to a limited number of digits.
well thanks for the help, kinda sucks that this is so limited but it was just something to keep me busy.
yeah, you can't use 8 byte to store that much information, I'm sorry.
Last edited on
Topic archived. No new replies allowed.