Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update leibniz.cpp #125

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 17 additions & 17 deletions src/leibniz.cpp
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
#include <cstdio>
#include <cstdlib>

unsigned rounds;
double pi = 1.0;
#include <iostream>
#include <fstream>

int main()
{
auto infile = std::fopen("rounds.txt", "r"); // open file
if (infile == NULL) {
perror("open file");
return EXIT_FAILURE;
}
if (std::fscanf(infile, "%u", &rounds) != 1) { // read from file
long rounds{0};

std::ifstream infile("rounds.txt"); // open file
if (!(infile >> rounds))
{
perror("read file");
return EXIT_FAILURE;
}
std::fclose(infile); // close file
infile.close(); // close file

double x {1.0};
double pi {1.0};

rounds += 2u; // do this outside the loop
rounds += 2; // do this outside the loop

for (unsigned i=2u ; i < rounds ; ++i) // use ++i instead of i++
for (long i {2} ; i < rounds ; i++) // use ++i instead of i++
{
double x = -1.0 + 2.0 * (i & 0x1); // allows vectorization
pi += (x / (2u * i - 1u)); // double / unsigned = double
x = -1.0 + 2.0 * (i & 0x1); // allows vectorization
pi += (x / (2 * i - 1)); // double / unsigned = double
}

pi *= 4;
std::printf("%.16f\n", pi); // print 16 decimal digits of pi
std::cout.precision(16);
std::cout << pi; // print 16 decimal digits of pi
return EXIT_SUCCESS;
}