전개 공식

        (ax + b)(cx + d) = acx^2 + (ad + bc)x + bd

에 기반을 둔 쉬운 곱셉법(일명 카라슈바 곱셈법)이다.

여기서 특히 a == b or a == c or b == d or c == d 인 경우이면

      ad + bc = s(c + d)  or ad + bc = a(b + d)

      or ad + bc = b(s + c) or ad + bc = c(a + b)

로 더 쉬운 곱셈 계산이 가능하다.

 

#!/usr/bin/python
# -*- coding: utf-8 -*-


# Filename: ezMult_02.py
#
# Execute: python ezMult_02.py
#
# See: http://zetcode.com/gui/pyqt4/widgets2/
# See: http://zetcode.com/gui/pyqt4/


import sys
import sys, random
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):
   
    def __init__(self):
        super(Example, self).__init__()
       
        self.ngame = 1
        self.npoint = 0
        self.doneflag = False
       
        self.initUI()
       
    def initUI(self):
        self.rect = QtCore.QRect(0, 30, 300, 220)
        self.xa = random.randint(11, 99)
        self.ya = random.randint(11, 99)
        self.lblXA = QtGui.QLabel(self)
        self.lblYA = QtGui.QLabel(self)
        self.lblYA.setFont(QtGui.QFont('Decorative', 16))
        self.lblXA.setFont(QtGui.QFont('Decorative', 16))
        self.lblXA.setText(str(self.xa))
        self.lblYA.setText(str(self.ya))
        self.lblXA.move(80, 60)
        self.lblYA.move(80, 80)

        self.lblAA = QtGui.QLabel(self)
        self.lblAA.setFont(QtGui.QFont('Decorative', 16))
        self.lblAA.setText("")
        self.lblAA.move(65, 90)

        self.lblBA = QtGui.QLabel(self)
        self.lblBA.setFont(QtGui.QFont('Decorative', 16))
        self.lblBA.setText("")
        self.lblBA.move(105, 110)

        self.lblCA = QtGui.QLabel(self)
        self.lblCA.setFont(QtGui.QFont('Decorative', 16))
        self.lblCA.setText("")
        self.lblCA.move(105, 120)

        self.lblOpa = QtGui.QLabel(self)
        self.lblOpa.setFont(QtGui.QFont('Decorative', 16))
        self.lblOpa.setText("X")
        self.lblOpa.move(40, 80)


        self.x = random.randint(11, 99)
        self.y = random.randint(11, 99)
        self.lblX = QtGui.QLabel(self)
        self.lblY = QtGui.QLabel(self)
        self.lblX.setText(str(self.x))
        self.lblY.setText(str(self.y))
        self.lblX.move(160, 40)
        self.lblY.move(160, 60)
        self.lblOp = QtGui.QLabel(self)
        self.lblOp.setText("X")
        self.lblOp.move(120, 60)
       
       
        self.lbl = QtGui.QLabel(self)
        self.lbl.move(60, 40)
        self.lbl.setHidden(True)

        self.lblScore = QtGui.QLabel(self)
        self.lblScore.setText("Score:")
        self.lblScore.move(10, 10)

        self.lblMsg = QtGui.QLabel(self)
        self.lblMsg.setText("Your first game")
        self.lblMsg.move(10, 255)

        self.lblScore.setFont(QtGui.QFont('Times New Roman', 12))
        self.lblMsg.setFont(QtGui.QFont('Times New Roman', 12))
       
       
        self.qleA = QtGui.QLineEdit(self)
        self.qleA.setFont(QtGui.QFont('Decorative', 20))
        self.qleA.setMaxLength(4)

        self.qleA.move(165, 90)
        self.qleA.resize(80, 30)

        self.qleB = QtGui.QLineEdit(self)
        self.qleB.setFont(QtGui.QFont('Decorative', 20))
        self.qleB.setMaxLength(3)
       
        self.qleB.move(165, 125)
        self.qleB.resize(60, 30)

        self.qleC = QtGui.QLineEdit(self)
        self.qleC.setFont(QtGui.QFont('Decorative', 20))
        self.qleC.setMaxLength(4)
       
        self.qleC.move(165, 170)
        self.qleC.resize(80, 30)

        if self.isSimple(self.xa, self.ya):
            self.redrawSimpleSubTable()
        else:
            self.redrawSubTable()
           
        if self.isSimple(self.x, self.y):
            self.redrawSimpleTable()
        else:
            self.redrawTable()
           
        self.btnExit = QtGui.QPushButton('Exit', self)
        self.btnExit.move(310, 60)
        self.btnExit.clicked.connect(self.doExit)
        self.btnExit.setEnabled(False)    

        self.btnMore = QtGui.QPushButton('More', self)
        self.btnMore.move(310, 120)
        self.btnMore.clicked.connect(self.moreGame)
        self.btnMore.setEnabled(False)  

        self.btnConfirm = QtGui.QPushButton('Ok', self)
        self.btnConfirm.move(310, 180)
        self.btnConfirm.clicked.connect(self.scoreGame)

        self.btnExit.setFont(QtGui.QFont('Arial', 12))
        self.btnMore.setFont(QtGui.QFont('Arial', 12))
        self.btnConfirm.setFont(QtGui.QFont('Arial', 12))


        self.qleA.textChanged[str].connect(self.onChanged)
       
        self.setGeometry(300, 300, 420, 280)
        self.setWindowTitle('Training Tool for Easy Multiplication')
        self.show()


    def moreGame(self):  
        self.update(self.rect)
          
        self.xa = random.randint(11, 99)
        self.ya = random.randint(11, 99)
        self.lblXA.setText(str(self.xa))
        self.lblYA.setText(str(self.ya))
       
        self.x = random.randint(11, 99)
        self.y = random.randint(11, 99)
        self.lblX.setText(str(self.x))
        self.lblY.setText(str(self.y))
       
        self.qleA.setText("")
        self.qleB.setText("")
        self.qleC.setText("")
       
        if self.isSimple(self.xa, self.ya):
            self.redrawSimpleSubTable()
        else:
            self.redrawSubTable()
           
        if self.isSimple(self.x, self.y):
            self.redrawSimpleTable()
        else:
            self.redrawTable()

        self.show()
        self.qleA.setFocus(True)    # See: http://pyqt.sourceforge.net/Docs/PyQt4/qwidget.html
        self.btnMore.setEnabled(False)  
        self.btnConfirm.setEnabled(True) 

        if self.ngame == 1:
            self.lblMsg.setText("Your first game")
        elif self.ngame == 2:
            self.lblMsg.setText("Your second game")
        elif self.ngame == 3:
            self.lblMsg.setText("Your third game")
        elif self.ngame == 4:
            self.lblMsg.setText("Your fourth game")
        elif self.ngame == 5:
            self.lblMsg.setText("Your fFifh game")
        else:
            self.lblMsg.setText("Your %d-th game" % self.ngame)
        self.lblMsg.adjustSize()


    def scoreGame(self):
        c = int(self.qleC.text())
       
        if self.isSimple(self.x, self.y):
            if c == self.x*self.y:
                 self.npoint += 1
                 self.lblMsg.setText("Right!")
                 if self.npoint == 5 and self.npoint == self.ngame:
                     self.lblMsg.setText("Congratulation!!")
                 self.lblMsg.adjustSize()
            else:
                s3 = "%d -> %d" % (c,  self.x*self.y)
                self.lblMsg.setText("Wrong! (%s)" % s3)
                self.lblMsg.adjustSize()
        else:
            a = int(self.qleA.text())
            b = int(self.qleB.text())
            if a == int(self.x / 10)*int(self.y / 10)*100 + (self.x % 10)*(self.y % 10) and \
                         b == int(self.x / 10)*(self.y % 10) + (self.x % 10)*int(self.y / 10) and \
                         c == self.x*self.y:
                 self.npoint += 1
                 self.lblMsg.setText("Right!")
                 if self.npoint == 5 and self.npoint == self.ngame:
                     self.lblMsg.setText("Congratulation!!")
                 self.lblMsg.adjustSize()
            else:
                s1 = ""
                if a != int(self.x / 10)*int(self.y / 10)*100 + (self.x % 10)*(self.y % 10):
                    s1 = "%d -> %d" % (a,  int(self.x / 10)*int(self.y / 10)*100 + (self.x % 10)*(self.y % 10))
                s2 = ""
                if b !=int(self.x / 10)*(self.y % 10) + (self.x % 10)*int(self.y / 10):
                    if len(s1) > 0:
                        s2 = ", "
                    s2 += "%d -> %d" % (b, int(self.x / 10)*(self.y % 10) + (self.x % 10)*int(self.y / 10))
                s3 = ""
                if c != self.x*self.y:
                    if len(s2) > 0:
                        s3 = ", "
                    s3 += "%d -> %d" % (c,  self.x*self.y)
                self.lblMsg.setText("Wrong! (%s%s%s)" % (s1, s2, s3))
                self.lblMsg.adjustSize()
       
        self.lblScore.setText("Your current score is %d in %d tries," % (20*self.npoint, self.ngame))
        self.lblScore.adjustSize()

        self.ngame += 1

        if self.ngame <= 5:
            self.btnMore.setEnabled(True)   
            self.btnMore.setFocus(True)    
        else:
            self.btnExit.setEnabled(True)  
            self.btnExit.setFocus(True)  
            self.btnMore.setEnabled(False)    
        self.btnConfirm.setEnabled(False)   


    def isSimple(self, x, y):
        if int(x/10) == int(y/10) or x % 10 == y % 10    \
                    or int(x/10) == x % 10 or int(y/10) == y % 10:
            return True
        else:
            return False


    def redrawSimpleSubTable(self):
        self.lblAA.setHidden(True)
        self.lblBA.setHidden(True)
        ca = int(self.xa) * int(self.ya)
        if len(str(ca)) == 3:
            self.lblCA.setText(str(ca))
            self.lblCA.move(72, 109)
            self.lblCA.adjustSize()
        else:
            self.lblCA.setText(str(ca))
            self.lblCA.move(60, 109)
            self.lblCA.adjustSize()


    def redrawSimpleTable(self):
        self.qleA.setHidden(True)
        self.qleB.setHidden(True)
        c = int(self.x) * int(self.y)
        if len(str(c)) == 3:
            self.qleC.setMaxLength(3)
            self.qleC.move(213, 110)
            self.qleC.resize(60, 30)
        else:
            self.qleC.setMaxLength(4)
            self.qleC.move(195, 110)
            self.qleC.resize(80, 30)


    def redrawSubTable(self):
        self.lblAA.setHidden(False)
        self.lblBA.setHidden(False)
        aa = int(self.xa/10) * int(self.ya / 10) * 100 + (self.xa % 10) * (self.ya % 10)
        if len(str(aa)) == 3:
            self.lblAA.setText(str(aa))
            self.lblAA.move(72, 109)
            self.lblAA.adjustSize()
        else:
            self.lblAA.setText(str(aa))
            self.lblAA.move(60, 109)
            self.lblAA.adjustSize()

        ba = int(self.xa % 10) * int(self.ya / 10) +  int(self.xa / 10) * int(self.ya %10)
        if len(str(ba)) == 1:
             self.lblBA.setText(str(ba))
             self.lblBA.move(84, 133)
             self.lblBA.adjustSize()
        elif len(str(ba)) == 2:
             self.lblBA.setText(str(ba))
             self.lblBA.move(72, 133)
             self.lblBA.adjustSize()
        else:
             self.lblBA.setText(str(ba))
             self.lblBA.move(60, 133)
             self.lblBA.adjustSize()

        ca = int(self.xa) * int(self.ya)
        if len(str(ca)) == 3:
             self.lblCA.setText(str(ca))
             self.lblCA.move(72, 164)
             self.lblCA.adjustSize()
        else:
             self.lblCA.setText(str(ca))
             self.lblCA.move(60, 164)
             self.lblCA.adjustSize()


    def redrawTable(self):
        self.qleA.setHidden(False)
        self.qleB.setHidden(False)
        a = int(self.x/10) * int(self.y / 10)
        if len(str(a)) == 1:
            self.qleA.setMaxLength(3)
            self.qleA.move(213, 110)
            self.qleA.resize(60, 30)
        else:
            self.qleA.setMaxLength(4)
            self.qleA.move(195, 110)
            self.qleA.resize(80, 30)

        b = int(self.x % 10) * int(self.y / 10) +  int(self.x / 10) * int(self.y %10)
        if len(str(b)) == 1:
             self.qleB.setMaxLength(1)
             self.qleB.move(235, 145)
             self.qleB.resize(20, 30)
        elif len(str(b)) == 2:
             self.qleB.setMaxLength(2)
             self.qleB.move(213, 145)
             self.qleB.resize(40, 30)
        else:
             self.qleB.setMaxLength(3)
             self.qleB.move(195, 145)
             self.qleB.resize(60, 30)

        c = int(self.x) * int(self.y)
        if len(str(c)) == 3:
            self.qleC.setMaxLength(3)
            self.qleC.move(213, 190)
            self.qleC.resize(60, 30)
        else:
            self.qleC.setMaxLength(4)
            self.qleC.move(195, 190)
            self.qleC.resize(80, 30)


    def paintEvent(self, e):
        qp = QtGui.QPainter()
        qp.begin(self)
        self.drawLines(qp)
        qp.end()
       
    def drawLines(self, qp):
        penA = QtGui.QPen(QtCore.Qt.black, 1, QtCore.Qt.SolidLine)
        qp.setPen(penA)
        if self.isSimple(self.xa, self.ya):
            qp.drawLine(37, 103, 107, 103)
        else:
            qp.drawLine(37, 103, 107, 103)
            qp.drawLine(37, 156, 107, 156)
       
        pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)
        qp.setPen(pen)
        if int(self.x/10) == int(self.y/10) or self.x % 10 == self.y % 10    \
                    or int(self.x/10) == self.x % 10 or int(self.y/10) == self.y % 10:
            qp.drawLine(170, 100, 270, 100)
        else:
            qp.drawLine(170, 100, 270, 100)
            qp.drawLine(170, 185, 270, 185)

        qp.setFont(QtGui.QFont('Decorative', 20))
        self.lblX.setFont(QtGui.QFont('Decorative', 20))
        self.lblY.setFont(QtGui.QFont('Decorative', 20))
        self.lblX.setText(str(self.x))
        self.lblY.setText(str(self.y))
        self.lblX.move(230, 40)
        self.lblX.adjustSize()
        self.lblY.move(230, 70)
        self.lblY.adjustSize()
        self.lblOp.setFont(QtGui.QFont('Decorative', 20))
        self.lblOp.move(170, 70)
        self.lblOp.adjustSize()

 

    def onChanged(self, text):

        self.lbl.setText(text)
        self.lbl.adjustSize()       
       
    def doExit(self):
        sys.exit(0)


def main():
        app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

 

실행 중인 창:

 

 

 

Posted by Scripter
,

* PyQt 내려받기: http://www.riverbankcomputing.co.uk/software/pyqt/download

 (Qt Designer 의실행 파일은 %Python27_HOME%\Lib\site-packages\PyQt4\Designer.exe 이다.)

Qt Designer 는 Visual Studio 의 Visual Basic 개발 환경과 비슷한 Python GUI 개발 도구이다.

다음은 책  Hello World! Second Edition: Computer Programming for Kids and Other Beginners 의 제 20 장에 소개되어 있는 예제를 한국어로 번안한 것이다.

 

Qt Designer 를 실행하여 다음과 같이 "새 폼" 창에서 "Main Window" 를 선택하고 "생성" 버튼을 클릭한다.

 

 

 위젯

  텍스트

 objectName

 Push Button

 Celsius to Fahrenheit >>>

 btn_CtoF

 Push Button

 <<< Fahrenheit to Celsius

 btn_FtoC

 Label

 Celsius

 

 Label

 Fahrenheit

 

 Line Edit

 

 editCel

 Spin Box

 

 spinFahr

* 주의: 폰트 설정 시 한글명 폰트(예: 바탕)를 선택하면 에러가 난다. 

 

위와 같이 디자인된 폼을 파일명 tempconv.ui 으로 저장한다.

 

소스 파일 tempconv.py 의 내용

# -*- encoding: utf-8 -*-

# PyQt 를 이용하는 온도 변환 프로그램

import sys
from PyQt4 import QtCore, QtGui, uic

form_class = uic.loadUiType("tempconv.ui")[0]                 # UI 탑재

class MyWindowClass(QtGui.QMainWindow, form_class):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.setupUi(self)
        self.btn_CtoF.clicked.connect(self.btn_CtoF_clicked)  # 버튼에 이벤트 핸들러를
        self.btn_FtoC.clicked.connect(self.btn_FtoC_clicked)  #   묶는다.

    def btn_CtoF_clicked(self):                # CtoF 버튼의 이벤트 핸들러
        cel = float(self.editCel.text())         #
        fahr = cel * 9 / 5.0 + 32                 #
        self.spinFahr.setValue(int(fahr + 0.5))  #

    def btn_FtoC_clicked(self):                  # FtoC 버튼의 이벤트 핸들러
        fahr = self.spinFahr.value()             #
        cel = (fahr - 32) / 9.0 * 5
        self.editCel.setText(str(cel))           #

app = QtGui.QApplication(sys.argv)
myWindow = MyWindowClass(None)
myWindow.show()
app.exec_()

 

버튼에 이벤트 핸들러를 묶어 주는 구문은

                  버튼명.clicked.connect(메소드명) 

이다.

 

실행하기:

프롬프트> python convtemp.py

 

 

Posted by Scripter
,

EditPlus3 의 메뉴에서

   도구(T) -----> 기본 설정(P) ...

을 택하고 기본 설정 창에서 아래와 같이 "사용자 도구" 항목을 지정한다.

 

 

 Python3 용 소스 파일 helloPython3.py 를 아래 처럼 작성하고 저장한 후 Ctrl+1 (숫지 1) 키를 누른다. (파일 저장시에는 BOM 없는 UTF-8 인코딩으로 지정한다.)

 

 

Posted by Scripter
,

ncurses(또는 curses) 는 Linux/Unix 계열의 환경에서 VT100 등의 터미널과 호환되는 윈도우형 입출력 라이브러이다. 이를 이용하면 윈도우의 임의의 위치에 출력도 하고, 임의의 위치에서 입력을 받을 수도 있다.

* 카라슈바 곱셈 참조

다음은 Linux 나 Cygwin 환경에서 파이썬 2.7.x 로 실행되도록 작성된 소스이다.

 

# Filename: ezMult_003.py
#
#  Execute: python ezMult_003.py
#
#     Date: 2014. 1. 10.

import curses
import curses.textpad
import random


stdscr = curses.initscr()
curses.start_color()   #
curses.nonl()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)

# Initialize few color pairs
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_GREEN)
curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_GREEN)
curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_GREEN)
curses.init_pair(4, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
curses.init_pair(5, curses.COLOR_CYAN, curses.COLOR_BLACK)
curses.init_pair(6, curses.COLOR_WHITE, curses.COLOR_BLACK)
curses.init_pair(7, curses.COLOR_BLACK, curses.COLOR_WHITE)

x0 = int(random.random()*90) + 10
y0 = int(random.random()*90) + 10
z0 = x0*y0
s01 = int(x0/10)*int(y0/10)
s02 = (x0%10)*(y0%10)
t0 = int(x0/10)*(y0%10) + (x0%10)*int(y0/10)

stdscr.addstr(3, 4, "%4d" % x0)
stdscr.addstr(4, 3, "x%4d" % y0)
stdscr.addstr(5, 3, "-----")
stdscr.addstr(6, 4, "%2d%02d" % (s01, s02))
stdscr.addstr(7, 4, "%3d" % t0)
stdscr.addstr(8, 3, "-----")
stdscr.addstr(9, 4, "%4d" % z0)

x = int(random.random()*90) + 10
y = int(random.random()*90) + 10
z = x*y
s1 = int(x/10)*int(y/10)
s2 = (x%10)*(y%10)
t = int(x/10)*(y%10) + (x%10)*int(y/10)

o1 = 0
o2 = 0
o3 = 0
if s1 < 10:
    o1 = 1
if t < 100:
    o2 = 1
if z < 1000:
    o3 = 1

stdscr.addstr(3, 14, "%4d" % x)
stdscr.addstr(4, 13, "x%4d" % y)
stdscr.addstr(5, 13, "-----")
stdscr.addstr(8, 13, "-----")
stdscr.move(6, 14)
stdscr.refresh()

curses.nl()
curses.noecho()

win4 = curses.newwin(14, 48, 3, 28)
win5 = curses.newwin(2, 78, 21, 0)
   
win4.addstr(0, 0, "Ctrl-A Go to left edge of edit box.")
win4.addstr(1, 0, "Ctrl-B Cursor left.")
win4.addstr(2, 0, "Ctrl-D Delete character under cursor.")
win4.addstr(3, 0, "Ctrl-E Go to right edge of edit box.")
win4.addstr(4, 0, "Ctrl-F Cursor right.")
win4.addstr(5, 0, "Ctrl-G Terminate, returning the box's contents.")
win4.addstr(6, 0, "Ctrl-H Delete character backward.")
win4.addstr(7, 0, "Ctrl-J Terminate if the edit box is 1 line.")
win4.addstr(8, 0, "Ctrl-K Clear to end of line.")
win4.addstr(9, 0, "Ctrl-L Refresh screen.")

win4.refresh()
# win4.getch()

win1 = curses.newwin(1, 5, 6, 14)   # (h,w,y,x)
win2 = curses.newwin(1, 4, 7, 14)   # (h,w,y,x)
win3 = curses.newwin(1, 5, 9, 14)   # (h,w,y,x)
win1.bkgd(curses.color_pair(1))
win2.bkgd(curses.color_pair(1))
win3.bkgd(curses.color_pair(1))
win1.refresh()
win2.refresh()
win3.refresh()
win1.move(0,0)

box1 = curses.textpad.Textbox(win1, insert_mode=True)
box2 = curses.textpad.Textbox(win2, insert_mode=True)
box3 = curses.textpad.Textbox(win3, insert_mode=True)
a1 = box1.edit()
win2.move(0,0)
a2 = box2.edit()
win3.move(0,0)
a3 = box3.edit()

stdscr.move(15, 0)
stdscr.attron(curses.color_pair(6))

try:
    tmp1 = int(a1)
    tmp2 = int(a2)
    tmp3 = int(a3)
    stdscr.addstr(15, 0, "Your answers are")
    stdscr.addstr(16, 0, "            %4d"% int(a1))
    stdscr.addstr(17, 0, "            %3d"% int(a2))
    stdscr.addstr(18, 0, "            %4d"% int(a3))

    stdscr.addstr(15, 20, "Right answers are")
    stdscr.addstr(16, 20, "             %2d%02d"% (s1, s2))
    stdscr.addstr(17, 20, "             %3d"% t)
    stdscr.addstr(18, 20, "             %4d"% z)

    if int(a1) == s1*100 + s2 and int(a2) == t and int(a3) == z:
     stdscr.addstr(20, 0, "Yours are right... ")
    else:
     stdscr.addstr(20, 0, "Yours are wrong... ")

    stdscr.getch()
except:
    stdscr.addstr(15, 0, "Some invalid charactres are found... ")
    stdscr.refresh()
    stdscr.getch()
finally:
    curses.nl()
    curses.nocbreak(); stdscr.keypad(0); curses.echo()
    curses.endwin()

 

Textbox 에서 입력 받을 스트링의 길이가 4인 경우 너비를 4+1 로 잡아야 하므로 배경색(녹색0의 너비가 4+1 로 나오는 것은 어쩔 수 없다. 한 Textbox 에서 입력을 마친 후 다음 Textbox 로 가려면 Enter Ctrl+G, Ctrl+J 키중 하나를 누르면 된다. Ctrl+D 는 커서가 놓인 곳의 글자를 지우는 키이고, Ctrl+H 는 커서 좌측의 글자를 지우면서 좌특으로 커서를 이동하는 키 (즉, Bacpspace 아 같은 역하를 하는 키이다.) Backspace 키는 Textbox 에서 동작하지 않는다. Ctrl+B 또는 키패드의 좌즉 화살표 키는 Textbox 안에서 좌측으로 한 칸씩 이동하는 키이고, Ctrl+F 또는 키패드의 우측 화살표 키는 Textbox 안에서 우측으로 한 칸씩 이동하는 키이다. 커서가 어느 Textbox 를 벗어나면 그 textbox 로는 다시 돌아갈 수 없다. 또 한 Textbox 의 우측 끝에 커서가 위치하면 글자 입력이 되지 않는다.

 

* 실행 결과:

 

 

 

Posted by Scripter
,

 

Python 언어 소스:

# Filename: testHexView_03.py
#
# Execute: python testHexView_03.py [filename]
# Execute: ipy testHexView_03.py [filename]

import os
import sys

def toHex(b):
    s = ""
    x1 = (b & 0xF0) >> 4
    x2 = b & 0x0F
    if x1 < 10:
        s += chr(x1 + ord('0'[0]))
    else:
     s += chr((x1 - 10) + ord('A'))
    if x2 < 10:
        s += chr(x2 + ord('0'))
    else:
        s += chr((x2 - 10) + ord('A'))
    return s

def toHex8(n):
    s = ""
    x1 = (n & 0xF0000000) >> 28
    x2 = (n & 0xF000000) >> 24
    x3 = (n & 0xF00000) >> 20
    x4 = (n & 0xF0000) >> 16
    x5 = (n & 0xF000) >> 12
    x6 = (n & 0xF0) >> 8
    x7 = (n & 0xF0) >> 4
    x8 = n & 0x0F
    if x1 < 10:
        s += chr(x1 + ord('0'))
    else:
        s += chr((x1 - 10) + ord('A'))
    if x2 < 10:
        s += chr(x2 + ord('0'))
    else:
        s += chr((x2 - 10) + ord('A'))
    if x3 < 10:
        s += chr(x3 + ord('0'))
    else:
        s += chr((x3 - 10) + ord('A'))
    if x4 < 10:
        s += chr(x4 + ord('0'))
    else:
        s += chr((x4 - 10) + ord('A'))
    s += " "
    if x5 < 10:
        s += chr(x5 + ord('0'))
    else:
        s += chr((x5 - 10) + ord('A'))
    if x6 < 10:
        s += chr(x6 + ord('0'))
    else:
        s += chr((x6 - 10) + ord('A'))
    if x7 < 10:
        s += chr(x7 + ord('0'))
    else:
        s += chr((x7 - 10) + ord('A'))
    if x8 < 10:
        s += chr(x8 + ord('0'))
    else:
        s += chr((x8 - 10) + ord('A'))
  
    return s

 

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print "Usage: python testHexView_03.py [filename]"
        sys.exit(1)

    fname = sys.argv[1]

    if not os.path.exists(fname):
        print "The file '%s' does not exist.\n" % fname
        sys.exit(1)
    elif os.path.isdir(fname):
        print "%s is a directory.\n" % fname
        sys.exit(1)

    fsize = os.path.getsize(fname)

    if fsize != None:
        print "The size of the file \"%s\" is %d." % (fname, fsize)
        if fsize == 0:
            sys.exit(1)
    print

    try:
        file2 = open(fname, "rb")
        n = 0
        dum = ""
        for i in range(fsize):
            if n % 16 == 0:
                sys.stdout.write("%s: " % toHex8(n & 0xFFFFFFFF))
             
            if n % 16 != 8:
                sys.stdout.write(" ")
            else:
                sys.stdout.write("-")

            a = file2.read(1)
            sys.stdout.write("%s" % toHex(int(ord(a))))
               
            if int(ord(a)) < int(ord(' ')) or int(ord(a)) & 0x80 != 0:
                dum += "."
            else:
                dum += a
               
            if n > 0 and n % 16 == 15:
                sys.stdout.write("  |%s|\n" % dum)
                dum = ""

            n += 1

        if n > 0 and n % 16 > 0:
            for i in range(16 - (fsize % 16)):
                sys.stdout.write("   ")
            sys.stdout.write("  |%s" %dum)
            for i in range(16 - (fsize % 16)):
                sys.stdout.write(" ")
            sys.stdout.write("|\n")
            dum = ""
    except IOError: 
        print "Error: the file \"%s\" cannot be read more." % fname
    finally:
        file2.close()
        print
        print "Read %d bytes\n" % n

 

 

예 1
Python으로 실행하기> python testHexView_03.py temp_1.bin
IronPython으로 실행하기> ipy testHexView_03.py temp_1.bin
Jython으로 실행하기> jython testHexView_03.py temp_1.bin
The size of the file "temp_1.bin" is 12.

0000 0000:  48 65 6C 6C 6F 20 74 68-65 72 65 0A              |Hello there.    |

Read 12 bytes

 

예 2
Python으로 실행하기> python testHexView_03.py myFile.ser
IronPython으로 실행하기> ipy testHexView_03.py myFile.ser
Jython으로 실행하기> jython testHexView_03.py myFile.ser
The size of the file "myFile.ser" is 130.

0000 0000:  AC ED 00 05 73 72 00 06-50 65 72 73 6F 6E 07 31  |....sr..Person.1|
0000 0010:  46 DB A5 1D 44 AB 02 00-03 49 00 03 61 67 65 4C  |F...D....I..ageL|
0000 0020:  00 09 66 69 72 73 74 4E-61 6D 65 74 00 12 4C 6A  |..firstNamet..Lj|
0000 0030:  61 76 61 2F 6C 61 6E 67-2F 53 74 72 69 6E 67 3B  |ava/lang/String;|
0000 0040:  4C 00 08 6C 61 73 74 4E-61 6D 65 71 00 7E 00 01  |L..lastNameq.~..|
0000 0050:  78 70 00 00 00 13 74 00-05 4A 61 6D 65 73 74 00  |xp....t..Jamest.|
0000 0060:  04 52 79 61 6E 73 71 00-7E 00 00 00 00 00 1E 74  |.Ryansq.~......t|
0000 0070:  00 07 4F 62 69 2D 77 61-6E 74 00 06 4B 65 6E 6F  |..Obi-want..Keno|
0000 0080:  62 69                                            |bi              |

Read 130 bytes

 

 

 

Posted by Scripter
,

아래의 파이썬용 소스를 실행시키자면 PyOpenGL 을 먼저 설치해야 한다.

소스의 구조는 C 언어 용으로 작성된 teapots,c 의 것과 거의 유사하다.

 

# Filename: teapots.py
#
# See Wiki: http://www.de-brauwer.be/wiki/wikka.php?wakka=PyOpenGL
# See Source: http://www.de-brauwer.be/wiki/wikka.php?wakka=PyOpenGLHelloWorld
# See C Source: http://www.glprogramming.com/red/chapter03.html

from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import sys

teapotList = 0

def initFun():
    global teapotList

    ambient = [ 0.0, 0.0, 0.0, 1.0 ]
    diffuse = [ 1.0, 1.0, 1.0, 1.0 ]
    specular = [ 1.0, 1.0, 1.0, 1.0 ]
    position = [ 0.0, 3.0, 3.0, 0.0 ]

    lmodel_ambient = [ 0.2, 0.2, 0.2, 1.0 ]
    local_view = [ 0.0 ]

    glLightfv(GL_LIGHT0, GL_AMBIENT, ambient)
    glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse)
    glLightfv(GL_LIGHT0, GL_POSITION, position)
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient)
    glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, local_view)

    glFrontFace(GL_CW)
    glEnable(GL_LIGHTING)
    glEnable(GL_LIGHT0)
    glEnable(GL_AUTO_NORMAL)
    glEnable(GL_NORMALIZE)
    glEnable(GL_DEPTH_TEST)
    # be efficient--make teapot display list
    teapotList = glGenLists(1)
    glNewList (teapotList, GL_COMPILE)
    glutSolidTeapot(1.0)
    glEndList ()


# Move object into position.  Use 3rd through 12th
# parameters to specify the material property.  Draw a teapot.
def renderTeapot(x, y, ambr, ambg, ambb, difr, difg, difb, specr, specg, specb, shine):
    global teapotList

    mat = [ 0.0, 0.0, 0.0, 0.0 ]

    glPushMatrix()
    glTranslatef(x, y, 0.0)
    mat[0] = ambr; mat[1] = ambg; mat[2] = ambb; mat[3] = 1.0
    glMaterialfv(GL_FRONT, GL_AMBIENT, mat)
    mat[0] = difr; mat[1] = difg; mat[2] = difb
    glMaterialfv(GL_FRONT, GL_DIFFUSE, mat)
    mat[0] = specr; mat[1] = specg; mat[2] = specb
    glMaterialfv(GL_FRONT, GL_SPECULAR, mat)
    glMaterialf(GL_FRONT, GL_SHININESS, shine * 128.0)
    glCallList(teapotList)
    glPopMatrix()


#  First column:  emerald, jade, obsidian, pearl, ruby, turquoise
#  2nd column:  brass, bronze, chrome, copper, gold, silver
#  3rd column:  black, cyan, green, red, white, yellow plastic
#  4th column:  black, cyan, green, red, white, yellow rubber
def displayFun():
    global teapotList

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    renderTeapot(2.0, 17.0, 0.0215, 0.1745, 0.0215, 0.07568, 0.61424, 0.07568, 0.633, 0.727811, 0.633, 0.6)
    renderTeapot(2.0, 14.0, 0.135, 0.2225, 0.1575, 0.54, 0.89, 0.63, 0.316228, 0.316228, 0.316228, 0.1)
    renderTeapot(2.0, 11.0, 0.05375, 0.05, 0.06625, 0.18275, 0.17, 0.22525, 0.332741, 0.328634, 0.346435, 0.3)
    renderTeapot(2.0, 8.0, 0.25, 0.20725, 0.20725, 1, 0.829, 0.829, 0.296648, 0.296648, 0.296648, 0.088)
    renderTeapot(2.0, 5.0, 0.1745, 0.01175, 0.01175, 0.61424, 0.04136, 0.04136, 0.727811, 0.626959, 0.626959, 0.6)
    renderTeapot(2.0, 2.0, 0.1, 0.18725, 0.1745, 0.396, 0.74151, 0.69102, 0.297254, 0.30829, 0.306678, 0.1)
    renderTeapot(6.0, 17.0, 0.329412, 0.223529, 0.027451, 0.780392, 0.568627, 0.113725, 0.992157, 0.941176, 0.807843, 0.21794872)
    renderTeapot(6.0, 14.0, 0.2125, 0.1275, 0.054, 0.714, 0.4284, 0.18144, 0.393548, 0.271906, 0.166721, 0.2)
    renderTeapot(6.0, 11.0, 0.25, 0.25, 0.25, 0.4, 0.4, 0.4, 0.774597, 0.774597, 0.774597, 0.6)
    renderTeapot(6.0, 8.0, 0.19125, 0.0735, 0.0225, 0.7038, 0.27048, 0.0828, 0.256777, 0.137622, 0.086014, 0.1)
    renderTeapot(6.0, 5.0, 0.24725, 0.1995, 0.0745, 0.75164, 0.60648, 0.22648, 0.628281, 0.555802, 0.366065, 0.4)
    renderTeapot(6.0, 2.0, 0.19225, 0.19225, 0.19225, 0.50754, 0.50754, 0.50754, 0.508273, 0.508273, 0.508273, 0.4)
    renderTeapot(10.0, 17.0, 0.0, 0.0, 0.0, 0.01, 0.01, 0.01, 0.50, 0.50, 0.50, 0.25)
    renderTeapot(10.0, 14.0, 0.0, 0.1, 0.06, 0.0, 0.50980392, 0.50980392, 0.50196078, 0.50196078, 0.50196078, 0.25)
    renderTeapot(10.0, 11.0, 0.0, 0.0, 0.0, 0.1, 0.35, 0.1, 0.45, 0.55, 0.45, 0.25)
    renderTeapot(10.0, 8.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.7, 0.6, 0.6, 0.25)
    renderTeapot(10.0, 5.0, 0.0, 0.0, 0.0, 0.55, 0.55, 0.55, 0.70, 0.70, 0.70, 0.25)
    renderTeapot(10.0, 2.0, 0.0, 0.0, 0.0, 0.5, 0.5, 0.0, 0.60, 0.60, 0.50, 0.25)
    renderTeapot(14.0, 17.0, 0.02, 0.02, 0.02, 0.01, 0.01, 0.01, 0.4, 0.4, 0.4, 0.078125)
    renderTeapot(14.0, 14.0, 0.0, 0.05, 0.05, 0.4, 0.5, 0.5, 0.04, 0.7, 0.7, 0.078125)
    renderTeapot(14.0, 11.0, 0.0, 0.05, 0.0, 0.4, 0.5, 0.4, 0.04, 0.7, 0.04, 0.078125)
    renderTeapot(14.0, 8.0, 0.05, 0.0, 0.0, 0.5, 0.4, 0.4, 0.7, 0.04, 0.04, 0.078125)
    renderTeapot(14.0, 5.0, 0.05, 0.05, 0.05, 0.5, 0.5, 0.5, 0.7, 0.7, 0.7, 0.078125)
    renderTeapot(14.0, 2.0, 0.05, 0.05, 0.0, 0.5, 0.5, 0.4, 0.7, 0.7, 0.04, 0.078125)
    glFlush()


def reshapeFun(w, h):
    glViewport(0, 0, w, h)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    if w <= h:
        glOrtho(0.0, 16.0, 0.0, 16.0*h/w, -10.0, 10.0)
    else:
        glOrtho(0.0, 16.0*w/h, 0.0, 16.0, -10.0, 10.0)
    glMatrixMode(GL_MODELVIEW)


def keyboardFun(key, x, y):
    if key == chr(27):
        sys.exit(0)


if __name__ == '__main__':
    glutInit()
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH)
    glutInitWindowSize(500, 600)
    glutInitWindowPosition(50,50)
    glutCreateWindow("Teapots")
    initFun()
    glutReshapeFunc(reshapeFun)
    glutDisplayFunc(displayFun)
    glutKeyboardFunc (keyboardFun)
    glutMainLoop()

 

실행하기: python teapots.py

실행 결과:

 

Posted by Scripter
,

아래의 파이썬용 소스를 실행시키자면 PyOpenGL 을 먼저 설치해야 한다.

소스의 구조는 C 언어 용으로 작성된 cube,c 의 것과 거의 유사하다.

 

# Filename: cube.py
#
# See Wiki: http://www.de-brauwer.be/wiki/wikka.php?wakka=PyOpenGL
# See Source: http://www.de-brauwer.be/wiki/wikka.php?wakka=PyOpenGLHelloWorld
# See C Source: http://www.glprogramming.com/red/chapter03.html

from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *

def initFun():
    glClearColor (0.0, 0.0, 0.0, 0.0)
    glShadeModel (GL_FLAT)
   

def displayFun():
    glClear(GL_COLOR_BUFFER_BIT)
    glColor3f(1.0, 1.0, 1.0)
    glLoadIdentity()             # clear the matrix
           # viewing transformation  */
    gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)
    glScalef(1.0, 2.0, 1.0)      # modeling transformation
    glutWireCube(1.0)
    glFlush()

def reshapeFun(w, h):
    glViewport(0, 0, w, h)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0)
    glMatrixMode(GL_MODELVIEW)


if __name__ == '__main__':
    glutInit()
    glutInitWindowSize(500, 500)
    glutInitWindowPosition(100, 100)
    glutCreateWindow("Draw a cube")
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
    glutDisplayFunc(displayFun)
    glutReshapeFunc(reshapeFun)
    initFun()
    glutMainLoop()

 

 

실행하기: python cube.py

실행 결과:

 

 

 

Posted by Scripter
,

음이 아닌 실수 A 의 평방근 sqrt(A) 를 구하는 Heron 의 방법:

        반복함수  g(x) = (x + A/x) / 2   를 이용

 

실수 A 의 n제곱근 root(n, A) 를 구하는 Newton-Raphson 의 방법

        반복함수  g(x) = ((n-1)*x + A/(x**(n - 1))) / n    를 이용

n = 2 인 경우에는 Newton-Raphson 의 방법이 Heron 의 방법과 동일하다.

(참조. http://en.wikipedia.org/wiki/Newton's_method )

 

Python 언어에는 지수 연산자 ** 를 (밑수)**(지수) 의 형식으로 언어 자체에서 지원하고 있다. 하지만 차후 필요한 데가 있을 것 같아서 이와 유사한 n 제곱 함수와 n 제곱근 함수를 구현해 보았다.

지수가 정수인 거듭제곱을 계산하는  함수도 nPow(), gPow, mPow() 세 개 구현해 놓았는데, 이들 세 함수는 절차적 언어의 성능상 재귀호출이 아니고 단순 반복 기법을 사용하는 함수이다. 이 세 함수 중 mPow() 의 성능이 가장 우수하다. 큰 지수의 경우 for 반복문의 반복회수를 따져 보면 성능 비교를 할 수 있을 것이다. (성능 비교를 위해 세 가지를 모두 소스에 남겨 두었다.) mPow() 함수는 n 제곱근을 구하는 재귀함수 newtonNthRoot(int, float) 의 구현에 사용되기도 한다. if ... else ... 구문이 많아 소스가 복잡하게 보일지 모르겠으나 이는 밑수나 지수가 음수이거나 0인 경우의 처리를 위함이다. 구현된 모든 함수의 구현에는 예외상황(예를 들어, 음수의 짝수 제곱근 같은 예외상황) 처리 과정이 있다. (참고로 Pythn 언어에는 double 타입이 없고, float 타입이 C, C++, Java, C# 언어의 double 타입에 해당한다.)

아래의 소스는 2.x 버전대의 파이썬에서 실행되도록 작성된 소스이다.

#!/usr/bin/env python
# -*- encoding: utf-8 -*-

# Filename: testNthRoot.py
#
#            Approximate square roots, cubic roots and n-th roots of a given number.
#
# Execute: python testNthRoot.py
#
#   Or
#
# Execute: jython testNthRoot.py
#
#   Or
#
# Execute: ipy testNthRoot.py
#
#   Or
#
# Compile: ipy %IRONPYTHON_HOME%\tools\scripts\pyc.py /main:testNthRoot.py /target:exe
# Execute: testNthRoot
#
# Date: 2013. 1. 6.
# Copyright (c) 2013 PH Kim  (pkim __AT__ scripts.pe.kr)


import math

MAX_ITER = 20000
M_EPSILON = 1.0e-15

#
# Compute the n-th power of x to a given scale, x > 0.
#
def nPow(a, n):
    if n > 0:
        if n == 1:
            return a
        else:
            if a == 0.0 or a == 1.0:
                return a
            elif a == -1.0:
                if n % 2 == 1:
                    return -1.0
                else:
                    return 1.0
            elif a < 0.0:
                if n % 2 == 1:
                    return -nPow(-a, n)
                else:
                    return nPow(-a, n)
            else:
                y = 1.0
                for i in range(n):
                    y *= a
                return y
    elif n == 0:
        return 1.0
    else:      #  when n < 0
        if a == 0.0:
            raise Error,'Negative powering exception of zero.'
        else:
            if n == -1:
                return 1.0/a
            else:
                return 1.0/nPow(a, -n)

 

#
# Compute the n-th power of x to a given scale, x > 0.
#
def gPow(a, n):
    if n > 0:
        if n == 1:
            return a
        else:
            if a == 0.0 or a == 1.0:
                return a
            elif a == -1.0:
                if n % 2 == 1:
                    return -1.0
                else:
                    return 1.0
            elif a < 0.0:
                if n % 2 == 1:
                    return -gPow(-a, n)
                else:
                    return gPow(-a, n)
            else:
                y = 1.0
                r = a
                m = 8*4 - 1            #  8*sizeof(int) - 1;
                one = 1
                for i in range(m + 1):
                    if (n & one) == 0:
                        y *= 1.0
                    else:
                        y *= r
                    r = r*r
                    one <<= 1
                    if one > n:
                        break
                return y
    elif n == 0:
        return 1.0
    else:      #  when n < 0
        if a == 0.0:
            raise Error,'Negative powering exception of zero.'
        else:
            if n == -1:
                return 1.0/a
            else:
                return 1.0/gPow(a, -n)

 

#
# Compute the n-th power of x to a given scale, x > 0.
#
def mPow(a, n):
    if n > 0:
        if n == 1:
            return a
        else:
            if a == 0.0 or a == 1.0:
                return a
            elif a == -1.0:
                if n % 2 == 1:
                    return -1.0
                else:
                    return 1.0
            elif a < 0.0:
                if n % 2 == 1:
                    return -mPow(-a, n)
                else:
                    return mPow(-a, n)
            else:
                y = 1.0
                r = a
                m = n
                while m > 0:
                    if (m & 0x1) == 1:
                        y *= r
                    r = r*r
                    m >>= 1
                return y
    elif n == 0:
        return 1.0
    else:      #  when n < 0
        if a == 0.0:
            raise Error,'Negative powering exception of zero.'
        else:
            if n == -1:
                return 1.0/a
            else:
                return 1.0/mPow(a, -n)

 

#
# Compute the square root of x to a given scale, x > 0.
#
def heronSqrt(a):
    if a < 0.0:
        raise ValueError,'Cannot find the sqrt of a negative number.'
    elif a == 0.0 or a == 1.0:
        return a
    else:
        x1 = a
        x2 = (x1 + a/x1)/2.0
        er = x1 - x2
        counter = 0
        while x1 + er != x1:
            x1 = x2
            x2 = (x1 + a/x1)/2.0
            er = x1 - x2
            if abs(er) < abs(M_EPSILON*x1):
                break
            counter += 1
            if counter > MAX_ITER:
                break
        if counter >= MAX_ITER:
            raise ValueError,'Inaccurate sqrt exception by too many iterations.'
        return x2


#
# Compute the cubic root of x to a given scale, x > 0.
#
def newtonCbrt(a):
    if a == 0.0 or a == 1.0 or a == -1.0:
        return a
    elif a < 0.0:
        return -newtonCbrt(-a)
    else:
        x1 = a
        x2 = (2.0*x1 + a/(x1*x1))/3.0
        er = x1 - x2
        counter = 0
        while x1 + er != x1:
            x1 = x2
            x2 = (2.0*x1 + a/(x1*x1))/3.0
            er = x1 - x2
            if abs(er) < abs(M_EPSILON*x1):
                break
            counter += 1
            if counter > MAX_ITER:
                break
        if counter >= MAX_ITER:
            raise Error,'Inaccurate cbrt exception by too many iterations.'
        return x2


#
# Compute the n-th root of x to a given scale, x > 0.
#
def newtonNthRoot(n, a):
    if n == 0:
        return 1.0
    elif n == 1:
        return a
    elif n > 0:
        if a == 0.0 or a == 1.0:
            return a
        elif a == -1.0:
            if n % 2 == 1:
                return a
            else:
                raise ValueError,'Cannot find the even n-th root of a negative number.'
        elif a < 0.0:
            if n % 2 == 1:
                return -newtonNthRoot(n, -a)
            else:
                raise ValueError,'Cannot find the even n-th root of a negative number.'
        elif a < 1.0:
            return 1.0/newtonNthRoot(n, 1.0/a)
        else:
            x1 = a
            xn = mPow(x1, n - 1)
            x2 = ((n - 1)*x1 + a/xn)/n
            er = x1 - x2
            counter = 0
            while x1 + er != x1:
                x1 = x2
                xn = mPow(x1, n - 1)
                x2 = ((n - 1)*x1 + a/xn)/n
                er = x1 - x2
                if abs(er) < abs(M_EPSILON*x1):
                    break
                counter += 1
                if counter > MAX_ITER:
                    break
            if counter >= MAX_ITER:
                raise ValueError, 'Inaccurate n-th root exception by too many iterations.'
            return x2
    else:
        if a == 0.0:
            raise Error, 'Cannot find the negative n-th root of zero.'
        else:
            return 1.0/newtonNthRoot(-n, a)


if __name__ == "__main__":

    x = 16.0
    u = math.sqrt(x)

    print "[ Testing heronSqrt(double) ]--------------------"
    print "x = %g" % x
    print "u = sqrt(%g) = %g" % (x, u)
    y = heronSqrt(x)
    print "y = heronSqrt(%g) = %g" % (x, y)
    print "y*y = %g" % (y*y)
    print

    print "[ Testing newtonCbrt(double) ]--------------------"
    x = -216.0
    print "x = %g" % x
    print "-exp(log(-x)/3.0) = %g" % -math.exp(math.log(-x)/3.0)
    w = newtonCbrt(x)
    print "w = newtonCbrt(%g) = %g" % (x, w)
    print "w*w*w = %g" % (w*w*w)
    print

    x = 729000000000.0
    print "x = %g" % x
    print "exp(log(x)/3.0) = %g" % math.exp(math.log(x)/3.0)
    w = newtonCbrt(x)
    print "w = newtonCbrt(%g) = %g" % (x, w)
    print "w*w*w = %g" % (w*w*w)
    print

    print "[ Testing newtonNthRoot(int, double) ]--------------------"
    z = newtonNthRoot(3, x)
    print "x = %g" % x
    print "z = newtonNthRoot(3, %g) = %g" % (x, z)
    print "z*z*z = %g" % (z*z*z)
    print

    x = 12960000000000000000.0
    z = newtonNthRoot(4, x)
    print "x = %g" % x
    print "z = newtonNthRoot(4, x) = newtonNthRoot(4, %g) =  %g" % (x, z)
    print "z*z*z*z = %g" % (z*z*z*z)
    print

    x = 1.0/12960000000000000000.0
    z = newtonNthRoot(4, x)
    print "x = %g" % x
    print "exp(log(x)/4.0) = %g" % math.exp(math.log(x)/4.0)
    print "z = newtonNthRoot(4, x) = newtonNthRoot(4, %g) =  %g" % (x, z)
    print "z*z*z*z = %g" % (z*z*z*z)
    print


    try:
        x = -4.0
        print "[ Test Exception heronSqrt(double) ]--------------------"
        print "x = %g" % x
        print "Calculating heronSqrt(%g)" % x
        y = heronSqrt(x)
        print "y = heronSqrt(%g) = %g" % (x, y)
        print "y*y = %g" % (y*y)
        print
    except ValueError, ex:
        print "%s\nCaught some exception in calculating heronSqrt(%g)" % (ex, x)
        print


    try:
        x = -4.0
        print "[ Test Exception in newtonCbrt(double) ]--------------------"
        print "x = %g" % x
        print "Calculating newtonCbrt(%g)" % x
        y = newtonCbrt(x)
        print "y = newtonCbrt(%g) = %g" % (x, y)
        print "y*y*y = %g" % (y*y*y)
        print
    except ValueError, ex:
        print "%s\nCaught some exception in calculating newtonCbrt(%g)" % (ex, x)
        print


    print "[ Test calculations by powering ]-----------------------------"
    x = 200.0
    z = newtonNthRoot(10, x)
    print "x = %g" % x
    print "exp(log(x)/10.0) = %g" % math.exp(math.log(x)/10.0)
    print "z = newtonNthRoot(10, x) = newtonNthRoot(10, %g) = %g" % (x, z)
    print "pow(z, 10) = %g" % math.pow(z, 10)
    print

    x = 3001.0
    z = newtonNthRoot(99, x)
    print "x = %g" % x
    print "exp(log(x)/99.0) = %g" % math.exp(math.log(x)/99.0)
    print "z = newtonNthRoot(99, x) = newtonNthRoot(99, %g) = %g" % (x, z)
    print "pow(z, 99) = %g" % math.pow(z, 99)
    print

    x = 3001.0
    z = newtonNthRoot(-99, x)
    print "x = %g" % x
    print "exp(log(x)/-99.0) = %g" % math.exp(math.log(x)/-99.0)
    print "z = newtonNthRoot(-99, x) = newtonNthRoot(-99, %g) = %g" % (x,z)
    print "1.0/pow(z, 99) = %g" % (1.0/math.pow(z, 99))
    print

    print "2.1**2.1 = pow(2.1, 2.1) = %g" % math.pow(2.1, 2.1)
    print "2.1**(-2.1) = pow(2.1, -2.1) = %g" % math.pow(2.1, -2.1)
    print "2.1**2.1 * 2.1**(-2.1) = pow(2.1, 2.1) * pow(2.1, -2.1) = %g" % (math.pow(2.1, 2.1)*math.pow(2.1, -2.1))
    print "2.1**2.1 = exp(2.1*log(2.1)) = %g" % math.exp(2.1*math.log(2.1))
    print "2.1**(-2.1) = exp(-2.1*log(2.1)) = %g" % math.exp(-2.1*math.log(2.1))
    print "2.1**2.1 * 2.1**(-2.1) = exp(2.1*log(2.1)) * exp(-2.1*log(2.1)) = %g" % (math.exp(2.1*math.log(2.1)) * math.exp(-2.1*math.log(2.1)))
    print


    k = 301
    x = -1.029
    t1 = nPow(x, k)
    t2 = gPow(x, k)
    t3 = mPow(x, k)
    print "math.pow(%g, %d) = %g" % (x, k,  math.pow(x, k))
    print "t1 = nPow(%g, %d) = %g" % (x, k,  t1)
    print "t2 = gPow(%g, %g) = %g" % (x, k, t2)
    print "t3 = mPow(%g, %g) = %g" % (x, k, t3)
    print "t1 / t2 = %g" % (t1 / t2)
    print "t1 - t2 = %g" % (t1 - t2)
    print "t1 == t2 ?", 
    if t1 == t2: print "yes"
    else: print "no"
    print "t1 / t3 = %g" % (t1 / t3)
    print "t1 - t3 = %g" % (t1 - t3)
    print "t1 == t3 ?", 
    if t1 == t3: print "yes"
    else: print "no"
    print "t2 / t3 = %g" % (t2 / t3)
    print "t2 - t3 = %g" % (t2 - t3)
    print "t2 == t3 ?", 
    if t2 == t3: print "yes"
    else: print "no"
    print

    print "Done."

"""
Output:
[ Testing heronSqrt(double) ]--------------------
x = 16
u = sqrt(16) = 4
y = heronSqrt(16) = 4
y*y = 16

[ Testing newtonCbrt(double) ]--------------------
x = -216
-exp(log(-x)/3.0) = -6
w = newtonCbrt(-216) = -6
w*w*w = -216

x = 7.29e+11
exp(log(x)/3.0) = 9000
w = newtonCbrt(7.29e+11) = 9000
w*w*w = 7.29e+11

[ Testing newtonNthRoot(int, double) ]--------------------
x = 7.29e+11
z = newtonNthRoot(3, 7.29e+11) = 9000
z*z*z = 7.29e+11

x = 1.296e+19
z = newtonNthRoot(4, x) = newtonNthRoot(4, 1.296e+19) =  60000
z*z*z*z = 1.296e+19

x = 7.71605e-20
exp(log(x)/4.0) = 1.66667e-05
z = newtonNthRoot(4, x) = newtonNthRoot(4, 7.71605e-20) =  1.66667e-05
z*z*z*z = 7.71605e-20

[ Test Exception heronSqrt(double) ]--------------------
x = -4
Calculating heronSqrt(-4)
Cannot find the sqrt of a negative number.
Caught some exception in calculating heronSqrt(-4)

[ Test Exception in newtonCbrt(double) ]--------------------
x = -4
Calculating newtonCbrt(-4)
y = newtonCbrt(-4) = -1.5874
y*y*y = -4

[ Test calculations by powering ]-----------------------------
x = 200
exp(log(x)/10.0) = 1.69865
z = newtonNthRoot(10, x) = newtonNthRoot(10, 200) = 1.69865
pow(z, 10) = 200

x = 3001
exp(log(x)/99.0) = 1.08424
z = newtonNthRoot(99, x) = newtonNthRoot(99, 3001) = 1.08424
pow(z, 99) = 3001

x = 3001
exp(log(x)/-99.0) = 0.922308
z = newtonNthRoot(-99, x) = newtonNthRoot(-99, 3001) = 0.922308
1.0/pow(z, 99) = 3001

2.1**2.1 = pow(2.1, 2.1) = 4.74964
2.1**(-2.1) = pow(2.1, -2.1) = 0.210542
2.1**2.1 * 2.1**(-2.1) = pow(2.1, 2.1) * pow(2.1, -2.1) = 1
2.1**2.1 = exp(2.1*log(2.1)) = 4.74964
2.1**(-2.1) = exp(-2.1*log(2.1)) = 0.210542
2.1**2.1 * 2.1**(-2.1) = exp(2.1*log(2.1)) * exp(-2.1*log(2.1)) = 1

math.pow(-1.029, 301) = -5457.93
t1 = nPow(-1.029, 301) = -5457.93
t2 = gPow(-1.029, 301) = -5457.93
t3 = mPow(-1.029, 301) = -5457.93
t1 / t2 = 1
t1 - t2 = 6.18456e-11
t1 == t2 ? no
t1 / t3 = 1
t1 - t3 = 6.18456e-11
t1 == t3 ? no
t2 / t3 = 1
t2 - t3 = 0
t2 == t3 ? yes

Done.
"""

 

 

Posted by Scripter
,

역삼각함수란 삼각함수의 역함수를 의미하고,

역쌍곡선함수란 쌍곡선함수의 역함수를 의미한다.

수학에서 sin 함수의 역함수는 arcsin 으로 표기되는데,

Python 언어에서는 math.asin() 함수로 이미 구현되어 있다.

이를 사용하기 위해서는 import 구문

import math

가 있으면 된다. 그러나 scipy 나 numpy 모듈을 사용할 때는 얘기가 달라진다.

sin 함수의 역함수가 scipy 모듈에서는 scipy.arcsin 으로, numpy 모듈에서는 numpy.arcsin 으로 구현되어 있다. (asin 이 아니라 arcsin 임에 주의하자.) 한편 mpmath 모듈에서는 mpmath.asin 으로 구현되어 았다. 이들 이용하기 위해서는 import 구문

import scipy

또는

import numpy

또는

import mpmath

가 각각 필요하다.

다음의 첫 두 개 소스는 scipy 와 numpy 의 차이 이외에는  똑 같다.

 

[ scipy 모듈을 이용하는 Python 소스 ]

#!/usr/bin/env python
# -*- encoding: utf-8 -*-

# Filename: testArcSineWithScipy.py
#
#            Approximate square roots, cubic roots and n-th roots of a given number.
#
# Execute: python testArcSineWithScipy.py
#
# Date: 2013. 1. 9.
# Copyright (c) 2013 PH Kim  (pkim __AT__ scripts.pe.kr)

import scipy as sp

x = -0.9
y = sp.arcsin(x)
print "x = %g" % x
print "y = sp.arcsin(x) = sp.arcsin(%g) = %.9f" % (x, y)
print "sp.sin(y) = sp.sin(%.9f) = %g" % (y, sp.sin(y))
print

x = 1.1
u = sp.arccosh(x)
v = sp.arcsinh(x)
print "x = %g" % x
print "u = sp.arccosh(x) = sp.arccosh(%g) = %.10f" % (x, u)
print "v = sp.arcsinh(x) = sp.arcsinh(%g) = %.10f" % (x, v)
print

print "sp.cosh(u) = sp.cosh(%.10f) = %g" % (u, sp.cosh(u))
print "sp.sinh(v) = sp.sinh(%.10f) = %g" % (v, sp.sinh(v))

"""
Output:
x = -0.9
y = sp.arcsin(x) = sp.arcsin(-0.9) = -1.119769515
sp.sin(y) = sp.sin(-1.119769515) = -0.9

x = 1.1
u = sp.arccosh(x) = sp.arccosh(1.1) = 0.4435682544
v = sp.arcsinh(x) = sp.arcsinh(1.1) = 0.9503469298

sp.cosh(u) = sp.cosh(0.4435682544) = 1.1
sp.sinh(v) = sp.sinh(0.9503469298) = 1.1
"""

 

[ numpy 모듈을 이용하는 Python 소스 ]

#!/usr/bin/env python
# -*- encoding: utf-8 -*-

# Filename: testArcSineWithNumpy.py
#
#            Approximate square roots, cubic roots and n-th roots of a given number.
#
# Execute: python testArcSineWithNumpy.py
#
# Date: 2013. 1. 9.
# Copyright (c) 2013 PH Kim  (pkim __AT__ scripts.pe.kr)

import numpy as np

x = -0.9
y = np.arcsin(x)
print "x = %g" % x
print "y = np.arcsin(x) = np.arcsin(%g) = %.9f" % (x, y)
print "np.sin(y) = np.sin(%.9f) = %g" % (y, np.sin(y))
print

x = 1.1
u = np.arccosh(x)
v = np.arcsinh(x)
print "x = %g" % x
print "u = np.arccosh(x) = np.arccosh(%g) = %.10f" % (x, u)
print "v = np.arcsinh(x) = np.arcsinh(%g) = %.10f" % (x, v)
print

print "np.cosh(u) = np.cosh(%.10f) = %g" % (u, np.cosh(u))
print "np.sinh(v) = np.sinh(%.10f) = %g" % (v, np.sinh(v))

"""
Output:
x = -0.9
y = np.arcsin(x) = np.arcsin(-0.9) = -1.119769515
np.sin(y) = np.sin(-1.119769515) = -0.9

x = 1.1
u = np.arccosh(x) = np.arccosh(1.1) = 0.4435682544
v = np.arcsinh(x) = np.arcsinh(1.1) = 0.9503469298

np.cosh(u) = np.cosh(0.4435682544) = 1.1
np.sinh(v) = np.sinh(0.9503469298) = 1.1
"""

 

 

[ mpmath 모듈을 이용하는 Python 소스 ]

#!/usr/bin/env python
# -*- encoding: utf-8 -*-

# Filename: testArcSineWithMpmath.py
#
#            Approximate square roots, cubic roots and n-th roots of a given number.
#
# Execute: python testArcSineMpmath.py
#
# Date: 2013. 1. 9.
# Copyright (c) 2013 PH Kim  (pkim __AT__ scripts.pe.kr)

import mpmath as mp

x = -0.9
y = mp.asin(x)
print "x = %g" % x
print "y = mp.asin(%g) = %.9f" % (x, y)
print "mp.sin(y) = mp.sin(%.9f) = %g" % (y, mp.sin(y))
print

x = 1.1
u = mp.acosh(x)
v = mp.asinh(x)
print "x = %g" % x
print "u = mp.acosh(%g) = %.9f" % (x, u)
print "v = mp.asinh(%g) = %.9f" % (x, v)
print

print "mp.cosh(u) = mp.cosh(%.9f) = %g" % (u, mp.cosh(u))
print "mp.sinh(v) = mp.sinh(%.9f) = %g" % (u, mp.sinh(v))

 

 

 

Posted by Scripter
,

역삼각함수란 삼각함수의 역함수를 의미하고,

역쌍곡선함수란 쌍곡선함수의 역함수를 의미한다.

수학에서 sin 함수의 역함수는 arcsin 으로 표기되는데,

Python 언어에서는 math.asin() 함수로 구현되어 있다.

이를 사용하기 위해서는 구문

import math

이 필요하다.

 

다음 소스는 Python, Jython, IronPython 중 어느 것으로 실행해도 같은 결과를 얻는다.

특히 IronPython 으로는 옵션 /target:exe 를 사용하여 컴파일하면 실행파일 testArcSine.exe 및 testArcSine.dll 파일을 얻는다, dll 파일이 있어야 exe 파일이 실행된다.

 

# -*- encoding: utf-8 -*-

# Filename: testArcSine.py
#
# Execute: python testArcSine.py
#
#  Or
#
# Execute: jython testArcSine.py
#
#  Or
#
# Execute: ipy testArcSine.py
#
#  Or
#
# Compile: ipy %IRONPYTHON_HOME%\Tools\Scripts\pyc.py /target:exe /main:testArcSine.py
# Execute: testArcSine
#
# Date: 2013. 1. 1.
# Copyright (c) pkim _AT_ scripts.pe.kr

import math

def sin(x):
            y = math.sin(x)
            return y

def asin(x):
            y = math.asin(x)
            return y

def sinh(x):
            y = math.sinh(x)
            return y

def cosh(x):
            y = math.cosh(x)
            return y

def asinh(x):
            y = math.log(x + math.sqrt(x*x + 1))
            return y

def acosh(x):
            y = math.log(x + math.sqrt(x*x - 1))
            return y


if __name__ == "__main__":
            x = -0.9
            y = asin(x)
            print "y = asin(%.1g) = %.9f" % (x,  y)
            print "sin(y) = sin(%.9f) = %.1g" % (y, sin(y))
            print

            x = 1.1
            u = acosh(x)
            print "u = acosh(%3.2g) = %.10f" % (x,  u)

            v = asinh(x)
            print "v = asinh(%3.2g) = %.10f" % (x,  v)

            print "cosh(u) = cosh(%.10f) = %3.2g" % (u,  cosh(u))
            print "sinh(v) = sinh(%.10f) = %3.2g" % (v,  sinh(v))

"""
Output:
y = asin(-0.9) = -1.119769515
sin(y) = sin(-1.119769515) = -0.9

u = acosh(1.1) = 0.4435682544
v = asinh(1.1) = 0.9503469298
cosh(u) = cosh(0.4435682544) = 1.1
sinh(v) = sinh(0.9503469298) = 1.1
"""

 

 

 

Posted by Scripter
,