Nugroho's blog.: April 2017

## Thursday, April 27, 2017

### "Auto" Gauss Naif in Delphi.

After do this in Python, now it's time to bring it back to Delphi, where all of this is started, :)

The heart of code lay on this one

```procedure tform1.gauss;
var i,j,k:integer; temp:real;
begin
for i:=1 to 9 do begin
for j:= 1 to i do begin
if t[i,j]<>0 then begin
temp:=t[i,j];
for k:= 1 to 10 do begin
if i=j then
t[j,k]:=t[j,k]/temp
else t[i,k]:=t[i,k]/temp - t[j,k];
end;
end;
end;
end;
//back subtitution
for i:=9 downto 1 do begin
x[i]:=t[i,10];
for j:=9  downto i do begin
if i<>j then
x[i]:=x[i]-x[j]*t[i,j];
end;
end;

```

You could say that it consists of zeroing lower tringle and normalizing the diagonal and then subtituting the value.

There's little failsafe code here, that is if we already have zero cell, don't proceed, or it will gave divided by zero error.

### Gauss Naif in Python

Okay, we've done the manual one, how about automatize it?

It's actually just a matter of finding the pattern on that code and after we found the loop, we just have to well... loop it, :)

## Wednesday, April 26, 2017

### Manual Gauss Jordan in Python.

What if we didn't do back substitution on Gauss Naif method but eliminate the rest instead? Nah, we get the Gauss Jordan here.

The idea is after we do operation to make the  lower-triangle have zero value,  we continue the operation until all the component in the upper-triangle have zero value too, and the diagonal have value of one.

Basically, the matrix becomes identity matrix. This way, we didn't need subtitution at all since all variables already has the exact value on the right side, :)

## Tuesday, April 25, 2017

### Manual Gauss Naif Elimination using Python

How about some manual matrix using manual Gauss just like always, but in Python? Okay, here it is.

I use tuple, I think it's just the same as array for this purpose.

I created matrix a with random value.  It's like linear equation system; three unknown variables with three equation. The purpose of this code is to find x1, x2 and x3.

Oh, in this case, its x0, x1 and x2, :)

## Monday, April 24, 2017

### That's Not Fair!

Maybe that's something come to our mind when we read this code. Yeah, that's forward dfference. It's designed to get the difference value using the point we calculate and the next one. That means the value will "lopsided" by nature, :)

## Friday, April 21, 2017

### Searching Multiple Roots Numerically.

This Python code only works with function that crossing x-axis.

The idea is we started from x=0 and walking to the positive direction and evaluating f(x) as we walk.

If there's change of the sign of f(x) from + to -, or vice versa, there must be a root in that area.

We began to surround it to find the-x that correspond to f(x)=0. That x value is the root.

After the root is found, we began to walk along x-axis again until found any sign change of f(x), or until x limit set on code.

## Thursday, April 20, 2017

### Manual Gauss Elimination on 3x3 Matrices in Delphi

I use this code in order to find its pattern.

Yes, there is many Gauss code out there. I plan to write it on next post about it. The dynamic Gauss Elimination code that could be implemented to any size of matrices.

But for now, let just settle on this.

https://youtu.be/csiFpdsrzzQ

## Wednesday, April 19, 2017

Again, :)

### Lagrange Polynomial Interpolation on Python.

It's a whole a lot easier than Newton's divided differences interpolation polynomial, because there is no divided difference part that need a recursive function.

## Tuesday, April 18, 2017

### Dewa.

Tentang religi, sepertinya @pitoyoamrih memang sangat berhati-hati sekali. Beliau menempatkan setting cerita bukan di dunia nyata kita (yang sudah penuh kontroversi religi), namun di dunia tersendiri yang bernama dunia wayang,  :)

Pun demikian, toh dewa-dewa di dunia wayang @pitoyoamrih tidak bertindak sebagai Tuhan, namun sebagai makhluk dengan tugas dan kemampuan khusus.

Bahkan di banyak cerita, para dewa ini cenderung  bertindak seperti oknum pejabat yang korup dan/atau sewenang-wenang sehingga perlu dilabrak oleh rakyatnya, :)

### Sukati dan Penyukilan.

Akhirnya saya tahu yang ini. Lagi-lagi @PitoyoAmrih menambal lubang di kamus wayang saya. :)

Kali ini tentang nama alias.

Saya sudah cukup akrab dengan nama alternatif di dunia wayang. Bahkan dengan beberapa gagrak yang berbeda.

Permadi, Pinten, Tangsen, Yayi Suni, kakang Suman, Bawor, Jaka Pitana, Suyudana, Jaladara, Kakrasana,...

## Monday, April 17, 2017

### Tak Terduga dan Menyenangkan.

Masih mbulet di buku @PitoyoAmrih, dengan gaya cerita beliau yang seperti orang ngobrol santai diantara teman.

Awalnya, saat memegang buku "Pertempuran Dua Pemanah. Arjuna-Karna" untuk pertama kali, saya sudah penuh dengan antisipasi bahwa ini bukan hanya tentang pertempuran dua orang itu.

Seperti di "Wisanggeni Membakar Api" atau "Antareja dan Antasena", saya menduga bahwa Pitoyo Amrih pasti akan menceritakan masa kecil Karna dan Permadi, yang memang dilakukan oleh beliau.

Namun ada tokoh "utama" lagi yang menyedot fokus saya yang disuguhkan beliau, ada pemanah lain. Adalah Ekalaya, Raden Bambang Ekalaya, raja Paranggelung, yang ternyata juga pemanah hebat. Yang sebelumnya hanya saya kenal sepintas lalu sebagai raja bergelar Prabu Palgunadi. Itupun, di otak saya, selalu tak lepas dari nama lain yang harus selalu hadir di imajinasi saya, meskipun saya tak tahu ada apa dengan dua nama tersebut. Nama itu adalah Palguna-Palgunadi.

Hal lain yang saya perhatikan adalah gaya bercerita Pitoyo Amrih di novel ini. Tadi sudah saya sebut bahwa beliau bercerita seperti ngobrol santai diantara teman. Ngobrol santai, tak ada jadwal, tak ada target, tapi tetap bikin nyaman. Bukankah itu tujuan santai diantara sahabat?

Ngobrol santai bagaimana? Yeah, saat kita ngobrol, saat kita sedang bicara tentang suatu topik, adakalanya topik itu merembet ke topik yang lain, yang juga merembet ke topik yang lainnya lagi, dan lainnya lagi, yang kemudian dengan santainya, mungkin sambil menyeruput kopi hangat yang tinggal separuh, kembali ke topik awal dengan mulus tanpa terkesan dipaksakan.

Hal itu terjadi di buku ini, betapa cerita masa kecil Karna tiba-tiba bergeser ke sayembara Kunti, geger Kangsadewa, dan kembali ke Karna lagi.

Saat ngobrol, kadangkala urutan kronologis juga sering tak beraturan. Kita bicara tentang kejadian hari ini yang merupakan akibat dari kejadian dua minggu yang lalu, yang direncanakan seminggu sebelum itu, berakibat dua minggu kemudian, dan akan kita lihat apakah besok ada akibat dari kejadian yang sekarang.

Hal yang sama saya kenali di buku ini saat tiba di bagian Ekalaya, berawal dari Ekalaya yang sudah lusuh, mundur ke Ekalaya saat masih di istana, maju sedikit ke bagian Ekalaya yang ditolak Durna, maju lagi, dan lagi.

Apakah membingungkan? Dari sisi cerita, ini justru menarik karena kita tahu sebuah akibat dulu, sehingga penasaran apa sebabnya, yang kemudian dijawab dengan elegant oleh Pitoyo Amrih. Sehingga jalan cerita jadi menarik, misteri atau rasa penasaran selalu jadi bahan bakar cerita yang menarik.

Akan lain halnya misal bagian Bambang Ekalaya diceritakan runtut secara kronologis, tak akan menarik karena kita akan tahu hasil akhirnya, atau mungkin malah tidak tahu sama sekali mau mengarah ke mana. Pitoyo Amrih tahu cara membuat cerita menjadi menarik. :)

#### Unexpected and Enjoyable.

It's still around @PitoyoAmrih book, with his story style that is like people chatting casually among friends.

Initially, when holding the book "Pertempuran 2 Pemanah. Arjuna-Karna", "Battle of the Two Archers. Arjuna-Karna" for the first time, I was full of anticipation that this was not just about the battle of the two people.

As in "Wisanggeni Membakar Api" or "Antareja and Antasena", I suspect that Pitoyo Amrih will surely tell about Karna and Permadi's childhood, which he did.

But there is another "main" character who appeared in the focus. There are other archers. It was Ekalaya, Raden Bambang Ekalaya, king of Paranggelung, who was also a great archer. Previously, I only knew at a glance as a king, Prabu Palgunadi. And even then, in my brain, it always can't be separated from other names that must always be present in my imagination, even though I don't know what/who the two names are. The name is Palguna-Palgunadi.

Another thing I noticed was the storytelling style of Pitoyo Amrih in this novel. I mentioned earlier that he told stories like casual chatting between friends. Chat casually, no schedule, no targets, but still comfortable. Isn't that a relaxed goal while chatting among friends?

Chat casually what? Yeah, when we talk, when we're talking about a topic, sometimes the topic spreads to other topics, which also spread to another topics, and more, which then casually, maybe while sipping a half cup of warm coffee, return to the original topic smoothly without being forced.

This happened in this book, how the story of  Karna's childhood suddenly shifted to the Kunti contest, commotion Kangsadewa, and returned to Karna again.

When we're chatting, sometimes the chronological order is also often irregular. We are talking about what happened today which was the result of the incident two weeks ago, which was planned a week before that, resulting in two weeks later, and we will see if tomorrow there will be a result of what is happening now.

The same thing I recognized in this book when I arrived in the part of Ekalaya, started from Ekalaya who was already worn out, retreated to Ekalaya while still in the palace, advanced slightly to the Ekalaya section which was rejected by Durna, advanced again, and again.

Is it confusing? In terms of the story, this is actually interesting because we know a result first, so we wondered why, which was then answered elegantly by Pitoyo Amrih. So that the storyline becomes interesting, mystery or curiosity is always became a fuel for an interesting story.

It will be different, for example, if Bambang Ekalaya's part is told in chronological order, it will not be interesting because we will know the end result, or maybe we don't know where it'll go at all. Pitoyo Amrih knows how to make stories interesting. :)

## Sunday, April 16, 2017

### Differentiation

We may already knew that on computational physic,  differentiation is used in Euler method to compute integration, or used in finite different method.

How about slope of the function? How do we use differentiation to differentiate a function?

If we have y = f(x), we will have slope value on, say, (x0 , f(x(0)) by differentiate it.

m = dy/dx = df(x)/dx.

For slope on x0, just compute it.

We could plot the linear function that have form

y = m x + c

## Saturday, April 15, 2017

### Creating (And Editing) Movie using iPhone, Macbook Air and Final Cut Pro.

I "clone" myself so I could play music in format trio, :)

.

What we need?

Of course:

• A camera, I use iPhone Camera, I have iPad Pro but...
• A tripod, I use iPhone because my iPad couldn't be mounted on this.
• A Mac, Final Cut Pro only run on Mac, I use Macbook Air.
• ehm, keyboard, guitar, bass guitar, whatever.
• (optional), sound recording device, my iPad have decent video-sound, but sadly my iPhone isn't (maybe defect product), so I use Behringer Xenyx with usb interface and connect it to my iPhone using usb to lightning adapter.
• a metronome, since I don't use iPad to recording, I play metronome apps an it, :) .
Okay then.

To make a video, first we have to make a video, :)

I, mean using camera. Here, the tripod is important. To be able to make a "triplet" on the same room, we have to record it sequentially using the same camera position.

So, I start with acoustic nylon guitar part from start to end, and immediately switch to bass guitar to play the bass part, and finally the keyboard part.

Keep in mind that we have to play at the different place at the room and avoid abrupt motion that could overlap each other.

Create a virtual zone for guitarist, bassist and keyboardist and 'they' have to play the instrument on their own zone.

I have to take this session twice because the first one didn't produce audio. It turn out that I have to tighten usb cable between iPhone and Xenyx (which I should do at the beginning, :) )

### Gibbous Moon

Baru ingat (atau sadar) tadi pagi saat ngantar Alfa Beta ke Budhe dan lihat bulan benjol di atas gunung.

Pantas semalam Beta bangun tengah malam, ndak bisa tidur lagi, trus minta pintu kamar ditutup sesaat setelah fokus ke pintu.

Dia biasanya saat mau tidur selalu minta pintu kamar dibuka lebar-lebar, kecuali tadi malam, tengah malam, :)

Lah, tapi kemarin kukannya  jumat malam sabtu, dan di Indonesia hantu memiliki jadwal standart untuk muncul di kamis malam jumat dan tak ada urusan sama bentuk bulan.

Yeah, seperti kita yang ndak lagi hanya makan nasi jagung atau tiwul, tetapi juga suka spaghetti dan pizza, kemungkinan hantu-hantu Indonesia juga berkembang.

Mereka mungkin selalu update informasi bahwa di luaran sana ada waktu keluar hantu yang beda, bukannya "Malam Jumat Kliwon" tetapi "Friday Night". Ada juga pesta hantu tahunan saat  hari jumat bertepatan dengan tanggal 13, yang di daerah jawa mungkin setara dengan tanggal Satu Suro.

Mungkin mereka juga berhubungan via media sosial dengan hantu-hantu luar negeri yang sharing bahwa ada komunitas hantu Eropa yang muncul saat bulan berbentuk benjol.

Dengan demikian, tidaklah mengherankan jika saat ini hantu-hantu bisa muncul setiap saat, karena mereka mungkin juga sudah bosen ratusan atau ribuan tahun melakukan hal yang sama terus menerus, :)

#edisiError

(Saya punya pengalaman sendiri saat saya masih suka tidur di luar rumah, di halaman lantai dua sambil lihat bulan dan bintang hampir tiap malam. Pada suatu malam, dini hari, bulan benjol tepat di atas kepala, tiba-tiba saya dipijit oleh seseorang (atau entah apa itu yang berbentuk orang) dengan fisik seperti nenek saya yang saya panggil "mak kecil" [saya punya tiga nenek resmi saat itu, :) ], nah nenek ini tidak mungkin ke tempat saya saat itu berbaring, lha wong rumahnya jauh. Setelah beberapa hari kemudian saya klarifikasi, ternyata dengan enteng semua sepakat bahwa itu bukan nenek saya [bahkan 'mak kecil' pun setuju], namun ibu dari nenek saya yang sudah meninggal [bahakan saat saya belum lahir] karena deskripsi fisiknya benar-benar tepat dan beliau memang punya style pijat yang unik. Wah... )

## Friday, April 14, 2017

### Numeric Integration using Python and Pylab

Pylab is Python module that contain NumPy and MatPlotlib.

Let f(x) = x^2 and we want to integrate it from 0 to 1.

Numerically we could use square method or trapezoidal (which is almost better).

### Masa Kecil

Salah satu detil dari @pitoyoamrih yang saya suka adalah cerita tentang masa kecil seorang tokoh wayang.

Kita tahu cerita lengkap tentang masa kecil tokoh wayang jarang ada di pakem utama. Hanya beberapa yang terkenal seperti Gatotkaca dan Wisanggeni, itupun dalam lakon  carangan.

Dengan kenyataan seperti itu (atau saya yang memang tidak tahu secara tuntas pakem utama pewayangan), buku-buku Pitoyo Amrih ini menjadi semacam hiburan yang menyegarkan.

Tentang masa kecil Karna bersama Adirata. Deskripsi watak Karna yang ambisius, nakal dan cenderung jahat kepada orang tua angkatnya menjadi pengantar yang tepat sebagai latar belakang masa dewasanya.

Permadi kecil, sebelum diusir dari istana, yang cuek cenderung sombong dan manja, tak mau membereskan busur dan tempat anak panah.

Narayana dan Kakrasana kecil di Widarakandang yang diasuh Demang Antagopa dan Nyai Sagopi.

Masa kecil para kurawa dijelaskan dengan rapi, tentang Destarata dan Gendari yang tidak pernah memperhatikan anaknya sama sekali, dan seratus saudara seumur yang tak terurus sehingga menjadikan pengantar kelakuan Kurawa saat sudah dewasa.

Masa kecil Wisanggeni mungkin sudah banyak yang tahu karena ada lakon Lahirnya Wisanggeni.

Nah saya suka cerita detil versi Pitoyo Amrih tentang masa kecil Antareja dan Antasena.

#### Childhood

One of the details of @pitoyoamrih that I like is the story of the childhood of a puppet character.

We know the full story about the childhood of puppet characters is rarely in the main Pakem. Only a few are famous like Gatotkaca and Wisanggeni, and even then in the Carangan (side story).

With such a reality (or it's just me, who  don't really know the complete Pakem of Wayang ), Pitoyo Amrih's books become a kind of refreshing entertainment.

About Karna's childhood with Adirata. Descriptions of Karna's ambitious, naughty and evil tendencies to her adoptive parents became the right introduction to her adult background.

Young Permadi, before being expelled from the palace, the ignorant tended to be arrogant and spoiled, not wanting to clear the bow and place the arrow.

Narayana and small Kakrasana in Widarakandang who are raised by Demang Antagopa and Nyai Sagopi.

The kurawa's childhood is neatly explained, about Destarata and Gendari who never pay attention to their children at all, and a hundred brothers during their unkempt years, making strong background of Kurawa's behavior as adults.

Wisanggeni's childhood may have been known because there was a play about the birth of Wisanggeni.

Now I like the detailed version of Pitoyo Amrih's version of Antareja's and Antasena's childhood.

### Delphi.

Still using Delphi?

Yup, it teach me about programming discipline, :)

## Thursday, April 13, 2017

### Flappy Bird Like in Delphi

Remember the infamous Flappy Bird? Yup, I will create the program based on that algorithm.

## Wednesday, April 12, 2017

### Newton Polynomial in Python

I wrote code for this in Delphi. This time I want to rewrite it in Python based on this wiki.

I use this set of data point
(0,0)
(1,1)
(2,4)
(4,16)
(5,25)

and I use xc=3 for the test data.

It's obvious that these sets of data points have quadratic form and f(xc) must have value of 9.

The heart of code lay on this

`def n(j,xc,x):    n = 1    for i in arange(j):        n *= (xc-x[i])    return ndef a(j,l,x,y):    if j==0:        return y[0]    elif j-l==1 :        return (y[j]-y[l])/(x[j]-x[l])    else:        return (a(j,l+1,x,y)-a(j-1,l,x,y))/(x[j]-x[l])        def N(xc,x,y):    N = 0    for j in range(len(x)):        N += a(j,0,x,y)*n(j,xc,x)        return N`

Look at the function a(j,l,x,y), that's recursive function to obtain Newton divided difference value.

the whole code is this
`from pylab import *def n(j,xc,x):    n = 1    for i in arange(j):        n *= (xc-x[i])    return ndef a(j,l,x,y):    if j==0:        return y[0]    elif j-l==1 :        return (y[j]-y[l])/(x[j]-x[l])    else:        return (a(j,l+1,x,y)-a(j-1,l,x,y))/(x[j]-x[l])        def N(xc,x,y):    N = 0    for j in range(len(x)):        N += a(j,0,x,y)*n(j,xc,x)        return Nx = []y = []#initial valuex.append(0)x.append(1)x.append(2)x.append(4)x.append(5)y.append(0)y.append(1)y.append(4)y.append(16)y.append(25)#for testingxc = 3yc = N(xc,x,y)print ''print xc, yc#plott = linspace(-7,7,100)u = N(t,x,y)plot(t,u)grid(True)show()`
.

here's the graphics

with another sets of data points, I have another result
(0,0)
(1,1)
(2,4)
(4,16)
(5,25)

## Tuesday, April 11, 2017

### Disorientasi

Kadang bingung sedang membaca buku @PitoyoAmrih yang mana, saking konsistennya. Banyak cerita yang ada di buku satu, menyisip di buku lainnya. Seakan empat atau lebih buku itu sebenarnya cuma satu buku yang dijilid bukan berdasarkan urutan, namun berdasarkan tema.

Saat membaca "Antareja dan Antasena", tiba-tiba serasa baca "Wisanggeni Membakar Api" saat tiba di bagian Antasena menjadi jagung.

Juga saat membaca "Pertempuran Dua Pemanah: Arjuna-Karna" serasa membaca sisipan dari (atau malah babon) dari "Kebaikan Kurawa".

Apakah itu berarti jelek? Tidak sama sekali. Ini berarti penulis memiliki satu plot besar yang dicurahkan di berbagai buku.

Eh, tentu saja memang ada plot besar bernama pakem di pewayangan,  :).

Hal yang menarik di sini, dengan berpegang pada plot besar, buku-buku Pitoyo Amrih memiliki konsistensi yang tinggi. Baca buku yang manapun tidak akan mengalami kebingungan tentang mana yang benar karena yang diceritakan bersumber dari hal yang sama. Namun ada juga detil-detil kecil yang menarik yang memang tidak ada di pakem atau (plot besar milik Pitaya Amrih sendiri), detil-detil ini membuat cerita menjadi menyenangkan karena tidak menjadi kaku karena pakem.

Banyak buku yang menjadi  kaku karena terlalu ikut pakem, atau buku yang terlalu aneh karena tidak mempedulikan pakem sama sekali (jadinya pembaca malah mengernyit sambil mikir "Arjuna kok gini?", "Samba kok gitu?" dsb )

Ohya, saya belum baca semua buku Pitoyo Amrih, dalam proses, tetapi sudah pasti jadi pengagum  beliau, :)

#### Disorientation

Sometimes I confused about reading the book @PitoyoAmrih, because it's too consistent. Many stories in a book, are inserted in other books. As if four or more books were actually just one book bound not by sequence, but by theme.

When reading "Antareja and Antasena", suddenly I read "Wisanggeni Membakar" when I arrived in the Antasena-became-Corn section.

Also when reading the "Pertempuran Dua Pemanah: Arjuna-Karna" it seemed that I read the insertion from (or even the baboon) of "Kebaikan Kurawa".

Does that mean bad? Not at all. This means that the author has one large plot devoted to various books.

Uh, of course there is indeed a big plot called the Pakem (Standart Plot) in Shadow Puppet story, :).

The interesting thing here is, by holding on to the big plot, Pitoyo Amrih's books have high consistency. Read any of his books. We will not experience a confusion about what is right because the story is from the same source. But there are also interesting little details that are not in the Pakem. These details make the story fun because it does not become rigid because not strict into Pakem.

Many books are stiff because they are too gripping, or books are too strange because they don't care about The Pakem at all (so the reader frowns while thinking "Why is  Arjuna like this?", " Why is Samba like that?" Etc.)

Oh yeah, I haven't read all of Pitoyo Amrih's books, it's still in the process, but I have definitely become his admirer, :)

### Newton Polinomial.

Here's code for Newton's divided differences interpolation polynomial (quite mouthful huh, :) ).

The purpose of this method is to create a function (polynomial) that passes through given set of data points.

I read data point from several edit box.

`procedure TForm1.Button3Click(Sender: TObject);var i:integer;begin  for i:=0 to n do begin    x[i]:=strToFloat(kx[i].Text);    y[i]:=strToFloat(ky[i].Text);  end;  xc:=strToFloat(kxc.Text);  yc:=fn(xc);  kyc.Text:=floatToStr(yc);  gambarNewton;end;`
.
kx and ky is tEdit created when button1 is clicked

`procedure TForm1.Button1Click(Sender: TObject);var i:integer;begin  button2.Enabled:=true;  button3.Enabled:=true;  button4.Enabled:=true;  button5.Enabled:=true;  n:=strToInt(edit1.Text);  kxc:=tEdit.Create(form1);       kyc:=tEdit.Create(form1);  kxc.Parent:=form1;              kyc.Parent:=form1;  kxc.Left:=36;                   kyc.Left:=72;  kxc.Width:=36;                  kyc.Width:=36;  kxc.Text:='0,5';  for i:=0 to n do begin    kx[i]:=tEdit.Create(form1);     ky[i]:=tEdit.Create(form1);    kx[i].Parent:=form1;            ky[i].Parent:=form1;    kx[i].Top:=36+36*i;             ky[i].Top:=36+36*i;    kx[i].Left:=36;                 ky[i].Left:=72;    kx[i].Width:=36;                ky[i].Width:=36;    kx[i].Text:=intToStr(i);        ky[i].Text:=intToStr(i);  end;end;`

xc is x coordinate where the corresponding y (yc) is obtained using Newton method by calling it

yc=fn(xc)

`function tform1.fn(xs:real):real;var i:integer;fs:real;begin  fs:=0;  for i:=0 to n do begin    fs:=fs+b(i,0)*c(xs,i);  end;  fn:=fs;end;`

the fn function call the two other function. The b function, a recursive contain divided difference like this

`function tform1.b(i,j:integer):real;begin  if i=0 then b:=y[0]    else if (i-j)=1 then      b:=(y[i]-y[j])/(x[i]-x[j])        else          b:=(b(i,j+1)-b(i-1,j))/(x[i]-x[j]);end;`

and c function, a recursive function (or you could rewrite it using simple for command)

`function tform1.c(xs:real;i:integer):real;begin  if i=0 then c:=1    else c:=(xs-x[i-1])*c(xs,i-1);end;`

and finally, draw the data and the function on image1

`fprocedure tform1.gambarNewton;var i,x0,y0:integer;px,py:real;begin  x0:=image1.Width div 2;               y0:=image1.Height div 2;  image1.Canvas.Brush.Color:=clLime;  image1.Canvas.Rectangle(0,0,image1.Width,image1.Height);  image1.Canvas.Brush.Color:=clWhite;  image1.Canvas.Pen.Color:=clBlack;  image1.Canvas.MoveTo(0,y0);           image1.Canvas.LineTo(image1.Width,y0);  image1.Canvas.MoveTo(x0,0);           image1.Canvas.LineTo(x0,image1.Height);  for i:=-300 to 300 do begin    px:=i/skala;                          py:=skala*fn(px);    image1.Canvas.Pixels[x0+i,y0-round(py)]:=clGreen;  end;  for i:=0 to n do begin    px:=x0+skala*x[i];                        py:=y0-skala*y[i];    image1.Canvas.Ellipse(round(px)-7,round(py)-7,round(px)+7,round(py)+7);  end;  px:=x0+skala*xc;                        py:=y0-skala*yc;  image1.Canvas.Brush.Color:=clred;  image1.Canvas.Ellipse(round(px)-7,round(py)-7,round(px)+7,round(py)+7);  image1.Canvas.Brush.Color:=clwhite;end;`

## Monday, April 10, 2017

### Short Function.

Here's my implementation of function according to The Power of 10;

"Restrict functions to a single printed page."

As bonus, I didn't use global variable if possible. So if a function or procedure need a variable from others, it have to be passed using parameter on that function.

If we look at the code below, we know that it can be rewritten using a long single procedure or function. But according The Power of Ten, a function should be as short as possible so it could be printed in a single page.

So, instead one long multiple page function, I write/break it as several short-single-printed-page functions. :)

`unit Unit1;interfaceuses  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  Dialogs, StdCtrls;type  TForm1 = class(TForm)    Edit1: TEdit;    Edit2: TEdit;    Button1: TButton;    Edit3: TEdit;    Edit4: TEdit;    procedure proses;    function konversi(a:real;c,d:char):string;    function konversiC(a:real;d:char):string;    function konversiF(a:real;d:char):string;    function konversiR(a:real;d:char):string;    function konversiK(a:real;d:char):string;    procedure Button1Click(Sender: TObject);  private    { Private declarations }  public    { Public declarations }  end;var  Form1: TForm1;implementation{\$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);begin  proses;end;`
`procedure tform1.proses;var  a:real;  s,b:string;  c,d:char;begin  a:=strToFloat(edit1.Text);  s:=edit2.Text;  c:=s[1];  s:=edit4.Text;  d:=s[1];  b:=konversi(a,c,d);  edit3.Text:=b;end;`
`function tform1.konversi(a:real;c,d:char):string;begin  case c of    'C':konversi:=konversiC(a,d);    'F':konversi:=konversiF(a,d)    'R':konversi:=konversiR(a,d)    'K':konversi:=konversiK(a,d)    else konversi:='error';  end;end;`
`function tform1.konversiC(a:real;d:char):string;begin  case d of    'C':konversiC:=floatToStr(a);    'F':konversiC:=floatToStr(a*9/5+32);    'R':konversiC:=floatToStr(a*4/5);    'K':konversiC:=floatToStr(a+273);    else konversiC:='Error';  end;end;`
`function tform1.konversiF(a:real;d:char):string;begin  case d of    'C':konversiF:=floatToStr((a-32)*5/9);    'F':konversiF:=floatToStr(a);    'R':konversiF:=floatToStr((a-32)*4/9);    'K':konversiF:=floatToStr((a-32)*5/9+273);    else konversiF:='Error';  end;end;`
`function tform1.konversiR(a:real;d:char):string;begin  case d of    'C':konversiR:=floatToStr(a*5/4);    'F':konversiR:=floatToStr(a*9/4+32);    'R':konversiR:=floatToStr(a);    'K':konversiR:=floatToStr(a*5/4+273);    else konversiR:='Error';  end;end;`
`function tform1.konversiK(a:real;d:char):string;begin  case d of    'C':konversiK:=floatToStr(a-273);    'F':konversiK:=floatToStr((a-273)*9/5+32);    'R':konversiK:=floatToStr((a-273)*4/5);    'K':konversiK:=floatToStr(a);    else konversiK:='Error';  end;end;end.`
.

### Another Turtle in Circle

There's always another way to solve something.

So, I have another code for "Turtle in Circle" code, :)

In the script below, I use turtle position to determine if it's still inside circle or not. If it outside circle, instead of send it to zero position, I send it to random position inside circle.

`import turtlefrom random import uniformimport numpy as npturtle.shape("turtle")#turtle.speed(1)x = 0y = 0rmax=40for i in range (1,1000):    a = uniform (-90,90) #angle    turtle.left(a)    d = uniform (-75,75) #distance    x = turtle.xcor()+d*np.cos(a*np.pi/180)    y = turtle.ycor()+d*np.sin(a*np.pi/180)    r = np.sqrt(x*x+y*y)    if r>rmax:        turtle.setx(uniform(-rmax,rmax))        turtle.sety(uniform(-rmax,rmax))        x = 0        y = 0    else:        turtle.forward(d)turtle.exitonclick() `
.

## Sunday, April 9, 2017

### Turtle in Circle

I use previous code and improve it so the turtle could only move at certain circle area.

`import turtlefrom random import uniformimport numpy as npturtle.shape("turtle")#turtle.speed(1)x = 0y = 0for i in range (1,1000):    a = uniform (-90,90) #angle    turtle.left(a)    d = uniform (-75,75) #distance    x += d*np.cos(np.pi*a/180)    y += d*np.sin(np.pi*a/180)    r = np.sqrt(x*x+y*y)    if r>40:        turtle.setx(0)        turtle.sety(0)        x = 0        y = 0    turtle.forward(d)turtle.exitonclick() `
.

### Anti MainStream.

Saat booming sepatu roda, Alfa malah sibuk berlatih skateboard, :D .

## Saturday, April 8, 2017

### Random Turtle Movement.

I use turtle module, the standard module, in Python.

The turtle movement has random direction (angle), and random distance (forward/backward).

`import turtlefrom random import uniformturtle.shape("turtle")turtle.speed(1)for i in range (1,100):    #random angle    a = uniform (-90,90)    turtle.left(a)    #random move    d = uniform (-100,100)    turtle.forward(d)turtle.exitonclick() `
.

### The Power of 10

Rules for Developing Safety-Critical Code:

Avoid complex flow constructs, such as goto and recursion.

All loops must have fixed bounds. This prevents runaway code.

Avoid heap memory allocation.

Restrict functions to a single printed page.

Use a minimum of two runtime assertions per function.

Restrict the scope of data to the smallest possible.

Check the return value of all non-void functions, or cast to void to indicate the return value is useless.

Use the preprocessor sparingly.

Limit pointer use to a single dereference, and do not use function pointers.

Compile with all possible warnings active; all warnings should then be addressed before release of the software.

## Friday, April 7, 2017

### Prime Number on Python

We've done it using Delphi, how about Python? Easy, :)

`for i in range (2,200):    prime = True    for j in range (2,i):        if i%j==0:             prime=False    if prime==True:        print i`
.

### Prime Number on Delphi

Using Delphi to generate prime number? Okay, there's some code out there with

if (i mod 2 <>0) and (i mod 3 <>0) and (i mod 5 <>0) and (i mod 7 <>0) then i is prime.

Don't use that.

That's just for prime number below 100.

Use this instead.

`var i,j:integer;   prime:boolean;begin  for i:=2 to 200 do begin    prime:=true;    for j:=2 to i-1 do begin      if i mod j=0 then prime:=false;    end;    if prime=true then memo1.Lines.Append(intToStr(i));  end;end;`
.

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) 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) 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)