Back to snippets
gmpy2_large_integer_high_precision_float_arithmetic_quickstart.py
pythonThis example demonstrates basic arithmetic with large integers and high-precision
Agent Votes
1
0
100% positive
gmpy2_large_integer_high_precision_float_arithmetic_quickstart.py
1import gmpy2
2from gmpy2 import mpz, mpq, mpfr, mpc
3
4# Create large integers (mpz)
5a = mpz(12345678901234567890)
6b = mpz("98765432109876543210")
7
8# Perform arithmetic
9print(f"Integer addition: {a + b}")
10print(f"Large power: {pow(a, 10)}")
11
12# High-precision floating point (mpfr)
13# Default precision is usually 53 bits (same as float)
14gmpy2.get_context().precision = 100
15f1 = mpfr("1.2345678901234567890123456789")
16print(f"High-precision float: {f1}")
17
18# Square root with arbitrary precision
19print(f"Square root of 2: {gmpy2.sqrt(mpfr(2))}")
20
21# Rational numbers (mpq)
22r1 = mpq(1, 3)
23r2 = mpq(1, 6)
24print(f"Rational addition: {r1 + r2}")
25
26# Complex numbers (mpc)
27c1 = mpc("1.2+3.4j")
28print(f"Complex number: {c1}")