Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - เริ่มต้นใช้งาน SymPy module


SymPy เป็นไลบรารี Python สำหรับคณิตศาสตร์เชิงสัญลักษณ์ มีจุดมุ่งหมายเพื่อให้เป็นระบบพีชคณิตคอมพิวเตอร์แบบเต็มรูปแบบ (CAS) ในขณะที่รักษารหัสให้ง่ายที่สุดเท่าที่จะเป็นไปได้เพื่อให้เข้าใจและขยายได้ง่าย SymPy เขียนด้วย Python ทั้งหมด SymPy ขึ้นอยู่กับ mpmath เท่านั้น ซึ่งเป็นไลบรารี Python แท้สำหรับการคำนวณเลขทศนิยมตามอำเภอใจ ทำให้ใช้งานง่าย

#กำลังติดตั้งโมดูล Sympy

pip install sympy

SymPy กำหนดประเภทตัวเลขต่อไปนี้:Rational และ Integer คลาส Rational แสดงจำนวนตรรกยะเป็นคู่ของจำนวนเต็มสองตัว คือ ตัวเศษและตัวส่วน ดังนั้น Rational(1, 2) แทน 1/2, Rational(5, 2) 5/2 และอื่นๆ คลาสจำนวนเต็มแสดงถึงจำนวนเต็ม

SymPy ใช้ mpmath ในพื้นหลัง ซึ่งทำให้สามารถคำนวณโดยใช้เลขคณิตที่มีความแม่นยำตามอำเภอใจ ด้วยวิธีนี้ ค่าคงที่พิเศษบางอย่าง เช่น exp, pi, oo (อนันต์) จะถือเป็นสัญลักษณ์และสามารถประเมินได้อย่างแม่นยำตามอำเภอใจ

ตัวอย่าง

# import everything from sympy module
from sympy import *
# you can't get any numerical value
p = pi**3
print("value of p is :" + str(p))
# evalf method evaluates the expression to a floating-point number
q = pi.evalf()
print("value of q is :" + str(q))
# equivalent to e ^ 1 or e ** 1
r = exp(1).evalf()
print("value of r is :" + str(r))
s = (pi + exp(1)).evalf()
print("value of s is :" + str(s))
rslt = oo + 10000
print("value of rslt is :" + str(rslt))
if oo > 9999999 :
   print("True")
else:
   print("False")

ผลลัพธ์

value of p is :pi**3
value of q is :3.14159265358979
value of r is :2.71828182845905
value of s is :5.85987448204884
value of rslt is :oo
True