Skip to content

Commit 54398dd

Browse files
Merge pull request #21 from DoctorLai/pi
Simple PI example
2 parents eed8e88 + d2a1b33 commit 54398dd

4 files changed

Lines changed: 73 additions & 0 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ Examples include (and will expand to):
3636
* [rot47](./rot47/)
3737
* [prefix-sum](./prefix-sum/)
3838
* [pi-monte-carlo](./pi-monte-carlo/)
39+
* [pi](./pi)
3940
* Data Structures
4041
* [map-with-unknown-key](./map-with-unknown-key/)
4142
* OOP

pi/Makefile

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# pull in shared compiler settings
2+
include ../common.mk
3+
4+
# per-example flags
5+
# CXXFLAGS += -pthread
6+
7+
## get it from the folder name
8+
TARGET := $(notdir $(CURDIR))
9+
SRCS := $(wildcard *.cpp)
10+
OBJS := $(SRCS:.cpp=.o)
11+
12+
all: $(TARGET)
13+
14+
$(TARGET): $(OBJS)
15+
$(CXX) $(CXXFLAGS) -o $@ $^
16+
17+
%.o: %.cpp
18+
$(CXX) $(CXXFLAGS) -c $< -o $@
19+
20+
run: $(TARGET)
21+
./$(TARGET) $(ARGS)
22+
23+
clean:
24+
rm -f $(OBJS) $(TARGET)
25+
26+
# Delegates to top-level Makefile
27+
check-format:
28+
$(MAKE) -f ../Makefile check-format DIR=$(CURDIR)
29+
30+
.PHONY: all clean run check-format

pi/main.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#include <iostream>
2+
#include <cstdlib>
3+
#include <iomanip>
4+
5+
int
6+
main(int argc, char* argv[])
7+
{
8+
long long iterations = 1000000;
9+
if (argc > 1) {
10+
iterations = std::atoll(argv[1]);
11+
}
12+
13+
double sum = 0.0;
14+
15+
for (long long i = 0; i < iterations; ++i) {
16+
double term = 1.0 / (2.0 * i + 1.0);
17+
if (i % 2 == 0)
18+
sum += term;
19+
else
20+
sum -= term;
21+
}
22+
23+
double pi = 4.0 * sum;
24+
25+
std::cout << std::setprecision(15);
26+
std::cout << pi << "\n";
27+
}

pi/tests.sh

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#!/bin/bash
2+
3+
set -ex
4+
5+
# Run the tests
6+
pi=$(./pi)
7+
8+
# Check that the result is within a reasonable range
9+
if (( $(echo "$pi < 3.0" | bc -l) )) ||
10+
(( $(echo "$pi > 3.2" | bc -l) )); then
11+
echo "Test failed: pi is out of range: $pi"
12+
exit 1
13+
else
14+
echo "Test passed: pi is within range: $pi"
15+
fi

0 commit comments

Comments
 (0)