Nugroho's blog.

Sunday, December 11, 2011

Operasi Matrik di Python


Python dapat melakukan operasi matrik semacam invers, normalisasi, determinan, mencari nilai eigen, trace, bahkan eksponen matrik.



Untuk dapat menggunakan operasi matrik di Python, kita membutuhkan modul numpy.

Berikut adalah contoh kode operasi matrik di python.

from numpy import *
from numpy.linalg import *
a=array(((1,2),(3,3)),float)
b=inv(a)
c=dot(a,b)
d=norm(a)
e=eig(a)
f=det(a)
g=trace(a)
h=exp(a)
i=log(a)
print 'matrik A ='
print a
print 'matrik invers A = B ='
print b
print 'AB ='
print c
print 'norm A ='
print d
print 'eigen A ='
print e
print 'det A ='
print f
print 'trace A ='
print g
print 'exp A ='
print h
print 'log A ='
print i
z=array(((0.0,0.0+1.j),(0.0-1.j,0)),complex)



Perhatikan bahwa python juga mendukung bilangan imajiner sehingga dapat digunakan untuk menghitung matrik kompleks

Menggambar Grafik di Python dengan Matplotlib


Ada beberapa modul di python untuk menggambar grafik, semacam graphy, pycairochart, matplotlib dll. Berikut adalah contoh plot grafik dari y=sin(x) dengan range x dari -10 s.d 10 dengan resolusi 0.1 satuan. Resolusi di sini adalah langkah dari -10 ke 10, jadi kita akan mem-plot sin(-10), sin(-9,9), sin(-9.8), ...




from matplotlib.pyplot import *
from visual import *
x=[]
x=arange(-10.,10.,0.1)
grid(True)
xlabel('Sumbu x')
ylabel('Sumbu y')
title('Jejak ')
plot(x,sin(x),'b-')
batas=10
ylim(-2,2)
xlim(-batas,batas)
show()


The Journey of Installing Matplotlib Python Module on OS X Lion

I need matplotlib to plot my python output when I am running my output function generator python code.

This post is a log of what I did to being able to install matplotlib 1.1.0 on python 2.7.2 on my Mac OS X Lion 10.7.2. Yet, it's unfinished job.


First, googling for matplotlib, sourceforge is official home fon it, but it's very slow, I coudn't even open download page with my sluggish connection. So, I searching other source.

Got it from kambing.ui.ac.id, it has pypi repositories, but when it opened, there is no package, just blank folder.

After further googling, I finally found http://pypi.python.org, pypi stand for python package index.

To be able to use pypi package, we have to install pip first, but before that install distribute using this command

curl http://python-distribute.org/distribute_setup.py | python
curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python

and then install matplotlib using pip, there is download activity, but got error at the end; must install numpy first, but it got error too as I didn't have GCC on my lion yet, aaarrrgghh... So, the hell of dependencies is begin...

So here I am, searching for 'light' GCC for my lion. I know I should install XCode 4 from Apple , it's free anyway, but I must face the fact that it's including 4.5GB download job, such a tedious job and wasting time; I just want to install 13 MB matplotlib.

I wish I can type the code below

pip install numpy
pip install matplotlib

(pray)

Saturday, December 10, 2011

Portable Python

When I wandering around, through virtual world, looking for Python reference of matplotlib, don't know what link I'd click, suddenly I'm landing in Portable Python page. Barely interested, not because it's not interesting, but I've already have python on my Mac and this Portable Python came with .exe download, such a tedious job if I try to run it on my machine (clearly, it's Windows apps). However, it's really useful distribution of Python.



At download section, it's recommended to download via torrent network, another interesting idea. Here some excerpt from Portable Python website



Portable Python is a Python® programming language preconfigured to run directly from any USB storage device, enabling you to have, at any time, a portable programming environment. Just download it, extract to your portable storage device or hard drive and in 10 minutes you are ready to create your next Python® application.

One of the most powerful dynamic programming languages that is used in a wide variety of application domains and is used at many companies and institutions around the world ( YouTube, Google, NASA, Firaxis Games, etc.).

iRig

Several weeks ago my iRig package has come, finally. I expect it'll come earlier but alas my home's in the middle of nowhere surounded with forest and mountain, even google map refuse to map my place, :). At least it comes safely at my front door.

 I planned to use it with Amplitube on my iPad. It worked flawlessy of course. A minor annoyance, it's built in jack is undetachable, so it's uncool if you planned to bring it on your front pocket.

 I'm surprised when the thing work well with my macbookpro too. My 13' MacBook Pro only have one port audio, either for input or output, so it's big 'yeah yeah' for me for be able to record my guitar on GarageBand AND listen it.

 iRig work with GarageBand for iPad too, and several music apps like digital effect apps for ipad (forget its name), I'm sure not just that. Sadly, amplitube didn't support more space for effect, eight slot effect will cool. Here some screenshot.

From Blogsy Photos
From Blogsy Photos
From Blogsy Photos
From Blogsy Photos

Script Python untuk Menghitung Nilai Input berupa Fungsi

Script di bawah adalah kode python sederhana untuk menghitung nilai sebuah fungsi yang dimasukkan sebagai input pada variabel tertentu. Fungsi yang diinputkan bisa bermacam-macam.



Kita bisa memasukkan fungsi kuadrat, sinus, pangkat tiga dan lain-lain sebagai input.

import sys,parser
from math import *
y = sys.argv[1]
x = int(sys.argv[2])
z = parser.expr(y).compile()
print 'Nilai fungsi ', y, ' pada x = ',x,' adalah ',eval(z)


Simpan dengan nama f.py. Jalankan dengan perintah

python f.py

Berikut beberapa hasilnya, lengkap beserta kesalahan-kesalahannya

Nugrohos-MacBook-Pro:python nugroho$ python f.py x**2 4
Nilai fungsi  x**2  pada x =  4  adalah  16
Nugrohos-MacBook-Pro:python nugroho$ python f.py sin(x) 4
-bash: syntax error near unexpected token `('
Nugrohos-MacBook-Pro:python nugroho$ python f.py 'sin(x)' 4
Nilai fungsi  sin(x)  pada x =  4  adalah  -0.756802495308
Nugrohos-MacBook-Pro:python nugroho$ python f.py 'sin(x)+x**2' 4
Nilai fungsi  sin(x)+x**2  pada x =  4  adalah  15.2431975047
Nugrohos-MacBook-Pro:python nugroho$ python f.py 'x**2+2x-8' 4
Traceback (most recent call last):
  File "f.py", line 5, in
    z = parser.expr(y).compile()
  File "", line 1
    x**2+2x-8
          ^
SyntaxError: invalid syntax
Nugrohos-MacBook-Pro:python nugroho$ python f.py 'x**2-2x-8' 4
Traceback (most recent call last):
  File "f.py", line 5, in
    z = parser.expr(y).compile()
  File "", line 1
    x**2-2x-8
          ^
SyntaxError: invalid syntax
Nugrohos-MacBook-Pro:python nugroho$ python f.py 'x**2-2*x-8' 4
Nilai fungsi  x**2-2*x-8  pada x =  4  adalah  0
Nugrohos-MacBook-Pro:python nugroho$ python f.py 'x**2+2*x-8' 4
Nilai fungsi  x**2+2*x-8  pada x =  4  adalah  16
Nugrohos-MacBook-Pro:python nugroho$ python f.py x**2+2*x-8 4
Nilai fungsi  x**2+2*x-8  pada x =  4  adalah  16
Nugrohos-MacBook-Pro:python nugroho$ python f.py "(x**2+2*x-8+sin(x))/(2*x+2)" 4
Nilai fungsi  (x**2+2*x-8+sin(x))/(2*x+2)  pada x =  4  adalah  1.52431975047
Nugrohos-MacBook-Pro:python nugroho$

Perhatikan bahwa lebih aman untuk menuliskan fungsi di dalam dua tanda petik (bisa petik satu ataupun petik dua).


Agar Python Lebih Manusiawi


Kita dapat menggunakan parser pada python untuk memasukkan input berupa fungsi atau persamaan. Namun, fungsi yang kita masukkan harus mengikuti aturan python, misal kita ingin fungsi y=x^2+2x+2, maka untuk input kita harus memasukkan  x**2+2*x. Memang tidak begitu merepotkan, namun akan lebih baik jika input yang kita masukkan sesuai dengan kebiasaan kita.


Untuk itu kita dapat menambahkan fungsi untuk mengubah x^2 menjadi x**2. Berikut adalah kode untuk melakukannya

>>> w='x^2'
>>> w.replace('^','**')
'x**2' 
>>> w
'x^2'
>>>

Hati-hati bahwa sintaks tersebut tidak benar-benar mengubah variabel w,dia tetap bernilai 'x^2' dan tidak dapat diproses. Untuk dapat mengubah string, maka kita perlu variabel baru untuk menampung dengan perintah y=w.replace('^','**'), atau tampung ke variabel itu sendiri dengan perintah w=w.replace('^','**'). Berikut adalah contohnya

>>> w='x^2'
>>> w
'x^2'
>>> w.replace('^','**')
'x**2'
>>> w
'x^2'
>>> y=w.replace('^','**')
>>> y
'x**2'
>>> w
'x^2'
>>> w=w.replace('^','**')
>>> w
'x**2'
>>> 

Dengan demikian pengguna dapat memberi input berupa x^2 atau x**2 untuk x pangkat dua.

Selain memakai perintah replace, kita juga bisa menggunakan regular expression menggunakan library re.
Berikut adalah hasil coba-coba menggunakan re.

Nugrohos-MacBook-Pro:~ nugroho$ python
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> s='persamaan pangkat 2''
  File "", line 1
    s='persamaan pangkat 2''
                           ^
SyntaxError: EOL while scanning string literal
>>> s='persamaan pangkat 2'
>>> s
'persamaan pangkat 2'
>>> import re
>>> re.sub("a",',',s)
'pers,m,,n p,ngk,t 2'
>>> s='persamaan pangkat 2'
>>> re.sub("\a",',',s)
'persamaan pangkat 2'
>>> s='persamaan pangkat 2'
>>> re.sub("\a",' ',s)
'persamaan pangkat 2'
>>> re.sub("a",' ',s)
'pers m  n p ngk t 2'
>>> s='persamaan pangkat 2'
>>> re.sub("a",'',s)
'persmn pngkt 2'
>>> s.replace('p','n')
'nersamaan nangkat 2'
>>> exit

323f (5) amp (1) android (12) apple (7) arduino (18) art (1) assembler (21) astina (4) ATTiny (23) blackberry (4) camera (3) canon (2) cerita (2) computer (106) crazyness (11) debian (1) delphi (39) diary (286) flash (8) fortran (6) freebsd (6) google apps script (8) guitar (2) HTML5 (10) IFTTT (7) Instagram (7) internet (12) iOS (5) iPad (6) iPhone (5) java (1) javascript (1) keynote (2) LaTeX (6) lazarus (1) linux (29) lion (15) mac (28) macbook air (8) macbook pro (3) macOS (1) Math (3) mathematica (1) maverick (6) mazda (4) microcontroler (35) mountain lion (2) music (37) netbook (1) nugnux (6) os x (36) php (1) Physicist (29) Picture (3) programming (189) Python (109) S2 (13) software (7) Soliloquy (125) Ubuntu (5) unix (4) Video (8) wayang (3) yosemite (3)