lab.cycu.org

  • Home
    • Site Map
    • reveal
    • blog
  • About
  • CK Design
    • Design Synthesis
    • Math
    • Pfaffians
  • Front-End
    • Javascript
    • Brython
      • W12 demo
    • Bootstrap
    • Fengari-Web
  • Design
    • Onshape
    • Solvespace
    • FreeCAD
    • Blender
  • Simulation
    • V-rep
    • Webots
    • Range
  • Realization
    • KLL3PP
    • Foosball
    • Publish
  • Back-End
    • Python
    • Cython
    • Metaheuristics
    • Pyslvs
    • Virtualbox
    • Ubuntu
Design Synthesis << Previous Next >> Pfaffians

Math

Babylonian Algorithms

1972_anchine_babylonian_algorithms_D_Knuth.pdf

Babylonian Square Root:

def BabylonianAlgorithm(number):
    if(number == 0):
        return 0;

    g = number/2.0;
    g2 = g + 1;
    while(g != g2):
        n = number/ g;
        g2 = g;
        g = (g + n)/2;

    return g;
print('The Square root of 0.3 =', BabylonianAlgorithm(0.3));


上述巴比倫演算法解平方根程式碼:

<!-- 導入 Brython 標準程式庫 -->
<script src="./../cmsimde/static/brython.js"></script>
<script src="./../cmsimde/static/brython_stdlib.js"></script>
<p></p>
<!-- 啟動 Brython -->
<script>
window.onload=function(){
// 設定 data/py 為共用程式路徑
brython({debug:1, pythonpath:['./../data/py']});
}
</script>
<!-- 利用 div 中 id 為 result 標註區, 承接 brython 運算結果列印 -->
<div id="result"></div>
<!-- 利用 input 標註及 id 為 n 換為 brython document 字串 -->
<p><input id="n" type="text" value="0.5"><br> 
<!-- 利用 button 標註與 id 為 button, 透過瀏覽器事件綁定 click 執行 Brython 函式 -->
<button id="button">Set Input Number</button></p>
<!-- 以下為 Brython 程式碼 -->
<script type="text/python3">
from browser import html, document

def BabylonianAlgorithm(number):
    if(number == 0):
        return 0

    g = number/2.0
    g2 = g + 1
    while(g != g2):
        n = number/ g
        g2 = g
        g = (g + n)/2

    return g

def printOutput(e):
    # 將 output 變數設為與 id 為 result 的標註區對應
    output = document["result"]
    # 先利用變數的 clear() 方法清除先前留下的內容
    output.clear()
    # 取 id 為 n 表單 input 中欄位的輸入 value 轉為 float 帶入函式運算後, 以 str 轉為字串然後插入 output 對應的 div 區域
    cal = html.B(str(BabylonianAlgorithm(float(document["n"].value))))
    output <= str(document["n"].value) + " 的平方根為: " + cal

# 將頁面中 id 為 button 的按鈕, 與滑鼠 click 事件綁定, 點擊後執行 printOutput,  注意函式以 event 作為輸入
document["button"].bind("click", printOutput)
</script>


Design Synthesis << Previous Next >> Pfaffians

Copyright © All rights reserved | This template is made with by Colorlib