Skip to content

Instantly share code, notes, and snippets.

@juliusgeo
Created March 10, 2023 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juliusgeo/ee778c8c005a8790fcb2a352de7d43f3 to your computer and use it in GitHub Desktop.
Save juliusgeo/ee778c8c005a8790fcb2a352de7d43f3 to your computer and use it in GitHub Desktop.
Pi In MongDB Aggregations
from pymongo import MongoClient
from decimal import localcontext
from math import sqrt, log2
from bson import Decimal128
from bson.decimal128 import create_decimal128_context
coll = MongoClient().db.coll
coll.drop()
def Dec(x):
with localcontext(create_decimal128_context()) as ctx:
return Decimal128(ctx.create_decimal(x))
coll.insert_one({"x":Dec(1.0),"a":Dec(1.0),"b":Dec(1.0/sqrt(2.0)),"t":Dec(1.0/4),"y":Dec(1.0),})
[coll.update_one({}, [
{"$set": {"y": {"$add": ["$a", 0.0]},},
},{"$set": {"a": { "$divide": [ { "$add": [ "$a", "$b" ] }, 2]},},
},{"$set": {"b": { "$sqrt": [ { "$multiply": ["$b", "$y" ] }]},},
},{"$set": {"t": { "$subtract": [ "$t", { "$multiply": ["$x", { "$pow": [ { "$subtract": ["$y", "$a"] }, 2]}]}]},},
},{"$set": {"x": { "$multiply": [ "$x", 2]}},
}
]) for _ in range(int(log2(34)))]
coll.update_one({}, [{"$addFields": {"pi": {"$divide": [{"$pow": [{"$add": ["$a", "$b"]}, 2]}, {"$multiply": [4, "$t"]}]}}}])
print(coll.find_one({}, projection={"pi":1, "_id": 0}))
@juliusgeo
Copy link
Author

{'pi': Decimal128('3.141592653589793111200356215084374')}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment