Skip to content

Commit 429c66a

Browse files
Actualización de calculo Pi()
solución con menos iteraciones, utilizando los promedios entre pares e impares se aproxima mas rápido al numero exacto
1 parent 8a164b6 commit 429c66a

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

Chapter1/calculating_pi.py

+21-2
Original file line numberDiff line numberDiff line change
@@ -14,18 +14,37 @@
1414
# See the License for the specific language governing permissions and
1515
# limitations under the License.
1616

17+
# solucion con menos iteraciones
18+
# tengo otra version mas simplificada pero la estoy probando, que calcula a la iteracion 30 y otra a la 10
1719

1820
def calculate_pi(n_terms: int) -> float:
1921
numerator: float = 4.0
2022
denominator: float = 1.0
2123
operation: float = 1.0
2224
pi: float = 0.0
25+
26+
pi_ant1: float = 4 # mem_pi_prev
27+
pi_ant2: float = 0 # men_pi_prev_prev
28+
pi_prom1: float = 0 # pi_mean_1
29+
pi_prom2: float = 0 # pi_mean_2
30+
2331
for _ in range(n_terms):
32+
pi_ant2 = pi_ant1 # backup1
33+
pi_ant1 = pi # backup2
2434
pi += operation * (numerator / denominator)
2535
denominator += 2.0
2636
operation *= -1.0
27-
return pi
2837

38+
pi_prom1 = (pi + pi_ant1) /2 # pi_mean_1
39+
pi_prom2 = (pi_ant1 + pi_ant2) /2 # pi_mean_2
40+
pi = (pi_prom1 + pi_prom2) /2 # pi_mean(pi_means)
41+
42+
return pi
2943

3044
if __name__ == "__main__":
31-
print(calculate_pi(1000000))
45+
#print(calculate_pi(350)) # PAR:POR ABAJO IMPAR:POR ARIBA
46+
pi1 = calculate_pi(99) # impar
47+
pi2 = calculate_pi(100) # par
48+
print(pi1)
49+
print(pi2)
50+
print( (pi1 + pi2) /2 ) # pi_mean(means)

0 commit comments

Comments
 (0)