Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
First try for CAS, SymPy with codegen
Search
Sponsored
·
SiteGround - Reliable hosting with speed, security, and support you can count on.
→
dv
June 05, 2016
Programming
720
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
First try for CAS, SymPy with codegen
dv
June 05, 2016
More Decks by dv
See All by dv
Python module in Rust
wdv4758h
0
200
Android Memory Leak Profiling - VMFive
wdv4758h
0
320
CPython's bug in feature that nobody uses
wdv4758h
0
130
Vim 手指健康操
wdv4758h
3
940
FreeBSD ports system
wdv4758h
0
160
Other Decks in Programming
See All in Programming
Skillsは効率化、Agentsは"自分の拡張"——Builder時代のエージェント編成(CC Night 2026)
wemra
1
170
ECSアプリログをFireLensでコスト削減しようとしたけど諦めた話 in Fargate×Node.js
akihisaikeda
2
4.2k
A2UI という光を覗いてみる
satohjohn
1
160
気づいたらRubyで100作品 ー クリエイティブコーディングが生活の一部になるまで / 100 Ruby Sketches Later: How Creative Coding Became Part of My Life
chobishiba
3
610
ふつうのFeature Flag実践入門
irof
8
4.2k
Mujeres en SEO Summit 2026 - Greatest Disaster Hits en Web Performance
guaca
0
200
過去最大のMCPアップデート! 2026-07-28 RC版の謎に迫る
licux
6
400
代数的データ型って何が嬉しいの? #frontend_phpcon_do
kajitack
8
3.8k
Webフレームワークの ベンチマークについて
yusukebe
0
180
LaravelLive Japan の裏方のすべて — 第188回 PHP勉強会@東京 (2026-06-24)
suguruooki
2
130
TSKaigi Night Talks 2026_TypeScriptでサプライチェーンの整合性を型に閉じ込める
geekplus_tech
0
410
決定論的オーケストレーションの設計と実装 / Design and Implementation of Deterministic Orchestration
nrslib
4
1.5k
Featured
See All Featured
JavaScript: Past, Present, and Future - NDC Porto 2020
reverentgeek
52
6k
Connecting the Dots Between Site Speed, User Experience & Your Business [WebExpo 2025]
tammyeverts
11
950
The SEO Collaboration Effect
kristinabergwall1
1
490
The untapped power of vector embeddings
frankvandijk
2
1.8k
[SF Ruby Conf 2025] Rails X
palkan
2
1.1k
The Myth of the Modular Monolith - Day 2 Keynote - Rails World 2024
eileencodes
28
3.5k
Context Engineering - Making Every Token Count
addyosmani
9
990
JAMstack: Web Apps at Ludicrous Speed - All Things Open 2022
reverentgeek
1
480
How to audit for AI Accessibility on your Front & Back End
davetheseo
0
450
Beyond borders and beyond the search box: How to win the global "messy middle" with AI-driven SEO
davidcarrasco
3
170
SEOcharity - Dark patterns in SEO and UX: How to avoid them and build a more ethical web
sarafernandez
0
210
How to Think Like a Performance Engineer
csswizardry
28
2.7k
Transcript
First try for CAS, SymPy with codegen 許邱翔 Chiu-Hsiang Hsu
[email protected]
Who am I ? • 我朋友都叫我 "dv" • Pythonista •
FOSS 熱愛 • 快畢業的大學生 • 即將進入四個月國軍 Online • 出來後準備找工作
先備知識 • Python 基本能力 • 一般 Python 套件安裝方式
Talk 目標: 會用 SymPy 協助處理你的數學問題!
調查
接下來會有 Bob 和 Alice 兩位同學一起參與
Bob:「等等,CAS 到底是什麼?」
Bob:「難道是 嗎?」
Computer Algebra System
符號運算
CAS (Computer Algebra System) 一些知名的軟體: • Maxima (GPL) • SageMath
(GPL) • SymPy (BSD License) • Mathematica (Proprietary) • Magma (Proprietary) • Maple (Proprietary) • MATLAB - Symbolic Math Toolbox (Proprietary)
Bob:「這聽起來好數學喔, 我快睡著了」
別擔心, 以下都是站在外行人的角度來看
Alice:「那什麼是 SymPy?」
什麼是 SymPy?
什麼是 SymPy? • Python 的 Library
什麼是 SymPy? • Python 的 Library • Open Source (BSD
License)
什麼是 SymPy? • Python 的 Library • Open Source (BSD
License) • 針對數學符號做處理 (Symbolic Computation)
什麼是 SymPy? • Python 的 Library • Open Source (BSD
License) • 針對數學符號做處理 (Symbolic Computation) • 安裝方便 ( 依賴的軟體相對少 )
基本 SymPy 使用
如何安裝 SymPy?
$ pip install sympy
為了讓沒安裝的人可以嘗試 ……
SymPy Live
SymPy Live live.sympy.org
Try Jupyter!
Try Jupyter! try.jupyter.org 1. 選 "New" 然後 "Python 3" 2.
輸入 "import sympy" 然後按 "Shift + Enter" 3. 現在你可以使用任何 SymPy 的功能了
SageMathCloud
SageMathCloud cloud.sagemath.com • 註冊 / 登入 • 建立新專案 • 在新專案中建立
Jupyter Notebook • 選擇 kernel
說文解字
SymPy
Python
Symbolic Python
符號!
什麼是 Symbolic? Symbolic • π • e Numeric • 3.141592653589793
• 2.718281828459045
建立 Symbol 3
x = Symbol ( "x" ) from sympy import Symbol
x, y, z = symbols ( "x, y, z" )
from sympy import symbols
var ( "x, y, z" ) from sympy import var
建立 Expression 2
x, y = symbols ( "x, y" ) expr =
x**2 + 2*x*y + y**2
各式數學操作 from sympy import sin, cos, ...
expr = sympify ( "x**2 + 2*x*y + y**2" )
from sympy import sympify
帶入求值 2
expr = sympify ( "x**2 + 2*x*y + y**2" )
result = expr.subs ( {"x": 1, "y": 2} )
expr = sympify ( "x**2 + 2*x*y + y**2" )
result = expr.evalf ( subs = {"x": 1, "y": 2} )
方程式化簡 1
expr = sympify ( "sin(x)**2 + cos(x)**2" ) new_expr =
expr.simplify ()
方程式展開 1
expr = sympify ( "(x + y)**2" ) new_expr =
expr.expand ()
解方程式 1
expr = sympify ( "x**4 - 1" ) result =
solve ( expr ) [-1, 1, -I, I] from sympy import solve
expr1 = sympify ( "x + y - 10" )
expr2 = sympify ( "x - y + 6" ) result = solve ( [expr1, expr2] ) {y: 8, x: 2}
等等, 講這麼多我當初到底是 什麼需求來用 SymPy 的?
讓電腦可以計算三角函數!
But how ?
逼近!
Chebyshev Approximation
Chebyshev Approximation 那是什麼鬼?我用的到嗎?
Chebyshev Approximation 那是什麼鬼?我用的到嗎? (你可能已經用過了)
Polynomial Approximation
目標:sin ( x ) 多項式逼近:a n xn + a n-1
xn-1 + … + a 1 x1 + a 0
取點
None
None
None
None
None
N 個點 可以解一元 N-1 次方程式 ( N-1 degree )
None
None
static const double half = 5.00000000000000000000e-01, /* 0x3FE00000, 0x00000000 */
S1 = -1.66666666666666324348e-01, /* 0xBFC55555, 0x55555549 */ S2 = 8.33333333332248946124e-03, /* 0x3F811111, 0x1110F8A6 */ S3 = -1.98412698298579493134e-04, /* 0xBF2A01A0, 0x19C161D5 */ S4 = 2.75573137070700676789e-06, /* 0x3EC71DE3, 0x57B1FE7D */ S5 = -2.50507602534068634195e-08, /* 0xBE5AE5E6, 0x8A2B9CEB */ S6 = 1.58969099521155010221e-10; /* 0x3DE5D93A, 0x5ACFD57C */ FreeBSD - msun (k_sin.c) 方程式係數
GNU C Library (s_sin.c) static const double sn3 = -1.66666666666664880952546298448555E-01,
sn5 = 8.33333214285722277379541354343671E-03, cs2 = 4.99999999999999999999950396842453E-01, cs4 = -4.16666666666664434524222570944589E-02, cs6 = 1.38888874007937613028114285595617E-03; 方程式係數
musl (__sin.c) static const double S1 = -1.66666666666666324348e-01, /* 0xBFC55555,
0x55555549 */ S2 = 8.33333333332248946124e-03, /* 0x3F811111, 0x1110F8A6 */ S3 = -1.98412698298579493134e-04, /* 0xBF2A01A0, 0x19C161D5 */ S4 = 2.75573137070700676789e-06, /* 0x3EC71DE3, 0x57B1FE7D */ S5 = -2.50507602534068634195e-08, /* 0xBE5AE5E6, 0x8A2B9CEB */ S6 = 1.58969099521155010221e-10; /* 0x3DE5D93A, 0x5ACFD57C */ 方程式係數
自己用 SymPy 寫 Chebyshev Approximation
None
轉成可執行 Function 9
lambdify ( args, expr, module=None ) from sympy import lambdify
lambdify ( x, x**x )
lambdify ( (x, y) , x**x + y**y )
lambdify ( x, x**x, "math" ) <function <lambda>>
lambdify ( x, x**x, "numpy" ) <function numpy.<lambda>>
lambdify ( x, x**x, "mpmath" ) <function <lambda>>
lambdify ( x, x**x, "numexpr" ) <function numexpr.<lambda>>
lambdify ( x, x**x, "sympy" ) <function <lambda>>
# NumPy universal function ufuncify ( args, expr, backend="numpy" )
from sympy.utilities.autowrap import ufuncify
# Python & NumPy's C API # and C compiler
ufuncify ( x, x**x ) <ufunc 'wrapper_module_0'>
# Cython ufuncify ( x, x**x, backend="cython") <function wrapper_module_0.autofunc_c>
# F2Py & Fortran compiler ufuncify ( x, x**x, backend="f2py")
<fortran object>
# Theano theano_function ( args, exprs ) from sympy.printing.theanocode import
theano_function
theano_function ( [x], [x**x] ) <theano.compile.function_module.Function at 0x7fd9a0bede48>
# broadcast and type theano_function ( [x], [x**x], dims={x: 1},
dtype={x: 'float64'}) <theano.compile.function_module.Function at 0x7fd9a0bede48>
Library 內建的 Chebyshev Approximation
poly, err = chebyfit ( sin, [0, pi/4], 10, error=True)
from mpmath import chebyfit, sin, pi poly: [2.53705546510064e-6, 4.83882390985545e-7, -0.000198913241162381, 2.96736201694264e-7, 0.00833322702020108, 2.28887435232138e-8, -0.166666669474202, 1.73888384312788e-10, 0.999999999995841, 1.63478544118895e-14]
poly, err = chebyfit ( sin, [0, pi/4], 10, error=True)
from mpmath import chebyfit, sin, pi err: 1.94337098561508e-14
找完逼近的方程式了 現在想要讓執行變快 怎麼辦?
NEED FOR SPEED
Bob:「肯定是 Python 直譯器不夠快, 我們來換一個實作吧」
Python 直譯器實作 • CPython ( 官方 ) • PyPy -使用
Python 的子集來實作,採用 JIT 與不同的 Garbage Collection 技術 • Pyston -基於 LLVM 實作 JIT • Jython -把 Python code 轉成 Java bytecode 跑在 JVM 上 • IronPython -用 .NET Framework 實作 • …
PyPy pypy.org • 專案狀態 ◦ Python 2.7 有支援 ◦ Python
3 目前指支援到 Python 3.3 (alpha) • 效能比較可以看 speed.pypy.org
Pyston github.com/dropbox/pyston • 由 Dropbox 於 2013 發起的專案 • 使用
C++11 撰寫 • 基於 LLVM 實作 JIT • 目前方向著重在 Python 2.7
CPython:「你這樣講就不對了, 怎麼可以怪我呢?」
Alice:「不要急著怪別人」
Alice:「其實你不需要 SymPy 了啊, 為什麼不寫成其他形式?」
自己重寫一遍好麻煩啊
SymPy codegen
codegen ( (name, expr), lang ) from sympy.utilities.codegen import codegen
要速度?何不試試編譯式語言?
None
C
codegen ( ("func", x**x), "c", header=False) [("func.c", "..."), ("func.h", "...")]
codegen ( ("func", x**x), "c", header=False) #include "func.h" #include <math.h>
double func(double x) { double func_result; func_result = pow(x, x); return func_result; }
codegen ( ("func", x**x), "c", header=False) #ifndef PROJECT__FUNC__H #define PROJECT__FUNC__H
double func(double x); #endif
Fortran
codegen ( ("func", x**x), "f95" ) [("func.f90", "..."), ("func.h", "...")]
喜歡類似 MATLAB 的語言? Octave
codegen ( ("func", x**x), "octave" ) [("func.m", "...")]
試試針對科學運算的新語言? Julia
codegen ( ("func", x**x), "julia" ) [("func.jl", "...")]
藏在 codegen 背後的重要資料-AST ( Expression Tree )
SymPy Expression Tree 把 SymPy 的 Expression Tree 轉成 DOT
語言描述 (接著可以用 Graphviz 這類工具轉成圖檔) from sympy.printing.dot import dotprint
x+2 SymPy Expression Tree
x**2 + 2*x*y + y**2 SymPy Expression Tree
x / (y + 42) SymPy Expression Tree
優化! Tree 操作!
SymPy Expression Tree sin(x)**2 + cos(x)**2 .simplify()
SymPy Expression Tree x**x + y**y .subs({x: 4})
Visitor Pattern
_print_<EXPR_CLASS>
_print ( expr ) _print_Rational ( expr ) _print_Number (
expr ) _print_AtomicExpr ( expr ) _print_Atom ( expr ) _print_Basic ( expr )
SymPy 運作流程圖(總結)
Symbol
Symbol Operation
Symbol Symbol Operation Operation Symbol Operation Operation Symbol Symbol
Symbol Operation Operation Symbol Symbol Symbol Operation Symbol
Symbol Operation Symbol C Fortran Octave Julia DOT LaTeX JavaScript
NumPy Theano Numexpr Python ...
C C compiler ufuncify Fortran Fortran compiler F2PY Cython Python
& Numpy C API module.so
SymPy 內其他 Modules
SymPy 內其他 Modules • Calculus • Physics • Lie Algebra
• Linear Algebra • Number Theory • Differential Geometry • Set Theory • ODE • PDE • Statistics • Logic • …
其他相關專案
SymPy Gamma
SymPy Gamma gamma.sympy.org
SymEngine github.com/symengine/symengine
SymEngine github.com/symengine/symengine (C++ 撰寫的 SymPy,為了提升效能)
基於 SymPy 的專案
基於 SymPy 的專案 • PyDy - Multibody Dynamics with Python
• SageMath - 有把 SymPy 整合進去 • SfePy - Simple Finite Elements in Python • …
本投影片將放在 speakerdeck.com/wdv4758h/first-try-for-cas- sympy-with-codegen
Thank you ! ! !
Questions ?