Created
March 10, 2023 22:16
-
-
Save juliusgeo/ee778c8c005a8790fcb2a352de7d43f3 to your computer and use it in GitHub Desktop.
Pi In MongDB Aggregations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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})) |
Author
juliusgeo
commented
Mar 10, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment