Tampilkan postingan dengan label Python. Tampilkan semua postingan
Tampilkan postingan dengan label Python. Tampilkan semua postingan

Senin, 13 Agustus 2018

Simple Python Machine Language

Berikut ini script Python 3 sederhana untuk mengubah dari arahan assembly sederhana menjadi bahasa mesin.


dict_op = {'ADD' : '0000', 'ADDC' : '0001', 'SUB' : '0010', 'SUBC' : '0011',
           'AND' : '0100', 'OR' : '0101', 'XOR' : '0110', 'NOT' : '0111',
           'SHL' : '1000', 'SHR' : '1001', 'ROL' : '1010', 'ROR' : '1011',
           'ADDI' : '0000', 'ADDCI' : '0001', 'SUBI' : '0010', 'SUBCI' : '0011',
           'SHLI' : '1000', 'SHRI' : '1001', 'ROLI' : '1010', 'RORI' : '1011',
           'LDRI' : '1100', 'STRI' : '1101', 'NOT' : '0000', 'MOV' : '0010',
           'SWP' : '0011', 'CMP' : '0100', 'LDR' : '0110', 'STR' : '0111',
           'MOVI' : '0000', 'CMPI' : '0010', 'B' : '0000', 'BEQ' : '0001',
           'BNE' : '0010', 'BLT' : '0011', 'BGT' : '0100', 'BR' : '1000',
           'BREQ' : '1001', 'BRNE' : '1010', 'BRLT' : '1011', 'BRGT' : '1100',
           'BRI' : '0000', 'BRIEQ' : '0001', 'BRINE' : '0010', 'BRILT' : '0011',
           'BRIGT' : '0100', 'MUL' : '0000', 'NOP' : '0000'}

dict_reg = {'R0' : '0000', 'R1' : '0001', 'R2' : '0010', 'R3' : '0011',
            'R4' : '0100', 'R5' : '0101', 'R6' : '0110', 'R7' : '0111',
            'R8' : '1000', 'R9' : '1001', 'R10' : '1010', 'R11' : '1011',
            'R12' : '1100', 'R13' : '1101', 'R14' : '1110', 'R15' : '1111'}

def main(filename):
        asmfile = open(filename,'r')
        a = asmfile.readlines()
        #print('asmfile: ', a)
        a = [i.upper() for i in [ x for x in a ]]
        #print('Upper case'a)
        a = [i.strip() for i in [ x for x in a ]]
        #print('Remove white space: ', a)
        a = filter(lambda x : x != '', a)
        #print('Remove empty element: ', a)
        a = [i.replace(' ',',') for i in [ x for x in a ]]
        #print('Change space with comma: ', a)
        a = [i.split(',') for i in [ x for x in a ]]
        #print('Split by comma: ', a)
        for ins in a:
                print('\nInstruction: %s %s, %s, %s' %(ins[0], ins[1], ins[2], ins[3]))
                if (ins[0] == 'ADD' or 'ADDC' or 'SUB' or 'SUBC' or 'AND' or 'OR' or 'XOR' or 'NOT' or 'SHL' or 'SHR' or 'ROL' or 'ROR'):
                        procedure1(ins)
                if (ins[0] == 'ADDI' or 'ADDCI' or 'SUBI' or 'SUBCI' or 'SHLI' or 'SHRI' or 'ROLI' or 'RORI'):
                        procedure2(ins)
                elif (ins[0] == 'NOT' or 'MOV' or 'SWP' or 'CMP' or 'LDR' or 'STR'):
                 #       procedure3(ins)
                elif (ins[0] == 'MOVI' or 'CMPI'):
                 #       procedure4(ins)
                elif (ins[0] == 'B' or 'BEQ' or 'BNE' or 'BLT' or 'BGT' 'BR' or 'BREQ' or 'BRNE' or 'BRLT' or 'BRGT'):
                 #       procedure5(ins)
                elif (ins[0] == 'BRI' or 'BRIEQ' or 'BRINE' or 'BRILT' or 'BRIGT'):
                 #       procedure6(ins)
                elif (ins[0] == 'MUL'):
                 #       procedure7(ins)
                elif (ins[0] == 'NOP'):
                        #dict_type = '0000'
                        #print('Opcode: ', dict_op[ins[0]])
                        #print('Destination operand: ', dict_reg[ins[1]])
                        #print('Source operand 1: ', dict_reg[ins[2]])
                        #print('Source operand 2: ', dict_reg[ins[3]])
                        #bincode_string = ' %s%s%s%s%s00000000' %(dict_type, dict_op[ins[0]], dict_reg[ins[1]], dict_reg[ins[2]], dict_reg[ins[3]])
                        #print('Binary code: %s' %bincode_string)
                        #hexcode_string = '0x'+'{0:0>8X}'.format(int(bincode_string, 2))
                        #print('Hex code: ', hexcode_string,'\n')
                        break

def procedure1(ins):
        print('Opcode: ', dict_op[ins[0]])
        print('Destination operand: ', dict_reg[ins[1]])
        print('Source operand 1: ', dict_reg[ins[2]])
        print('Source operand 2: ', dict_reg[ins[3]])
        dict_type = '0001'
        bincode_string = '%s%s%s%s%s' %(dict_type, dict_op[ins[0]], dict_reg[ins[1]], dict_reg[ins[2]], dict_reg[ins[3]])
        print('Binary code: %s' %bincode_string + 'XXXXXXXXXXXX')
        hexcode_string = '0x'+'{0:0>5X}'.format(int(bincode_string, 2))
        print('Hex code: ', hexcode_string + 'XXX')
        print('Let us assume X = 0, hence')
        print('Binary code: %s' %bincode_string + '000000000000')
        print('Hex code: ', hexcode_string + '000')

def procedure2(ins):
        print('Opcode: ', dict_op[ins[0]])
        print('Destination operand: ', dict_reg[ins[1]])
        print('Source operand: ', dict_reg[ins[2]])
        dict_type = '0010'
        bincode_string = ' %s%s%s%s' %(dict_type, dict_op[ins[0]], dict_reg[ins[1]], dict_reg[ins[2]])
        print('Binary code: %s' %bincode_string + 'imm16')
        hexcode_string = '0x'+'{0:0>4X}'.format(int(bincode_string, 2))
        print('Hex code: ', hexcode_string + 'imm16')
        print('Let us assume imm16 = 0, hence')
        print('Binary code: %s' %bincode_string + '0000000000000000')
        print('Hex code: ', hexcode_string + '000')
      

if __name__ == '__main__':
        main('demo.asm')


Dengan sample file code.asm yang diperlukan.

add r1,r2,r3
addc r3,r4,r5
sub r1,r2,r3
subc r13,r14,r15
and r12,r5,r6
or r7,r8,r9
xor r0,r10,r11

Sumber http://lang8088.blogspot.com

Rabu, 01 Agustus 2018

Python Opencv Analisis Histogram

Pagi hari menulis research paper ditemani dengan satu gelas kopi panas. Meski menjelang Natal dan tahun baru, tampaknya tidak ada gejala libur bagi engineer. Nasib.

Sebagai sambilan dan juga refreshing, goresan pena catatan ringan di blog yang kian absurd. Untuk artikel blog kali ini akan dibahas mengenai seri artikel dasar image processing dengan OpenCV dan Python. Pada bab ini dibahas singkat mengenai histogram.

Suatu histogram menawarkan garis besar gosip mengenai intensitas distribusi dari suatu image. Histogram menampilkan plot nilai pixel, disebut bin, mulai dari 0 sampai 255, untuk 8-bit, pada sumbu X dan jumlah pixel yang terkait di sumbu Y dari plot tersebut.

Beberapa hal yang perlu dipersiapkan, tentu saja OpenCV dan Python, berikutnya asumsikan file 'image.jpg' berada di satu direktori dengan file Python.




Script pertama, menampilkan histogram dari file 'image.jpg' tersebut.
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('image.jpg',0)
histogram = np.bincount(img.ravel(),minlength=256)
print(histogram)
plt.hist(img.ravel(),256,[0,256]);
plt.title('Histogram')
plt.xlim([0,256])
plt.show()

Berikut hasil histogram yang pertama.

Script kedua, menampilkan histogram RGB.
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('image.jpg')
color = ('b','g','r')
for i,col in enumerate(color):
    histr = cv2.calcHist([img],[i],None,[256],[0,256])
    plt.plot(histr,color = col)
    plt.xlim([0,256])
plt.legend(('Blue','Green','Red'), loc = 'upper right')
plt.title('Histogram')
plt.show()

Terdapat channel [0], [1], dan [2], untuk RGB. Sedangkan jikalau hanya menampilkan histogram gray scale cukup [0]. Berikut hasilnya.

Script ketiga, memakai mask untuk memilih region dari image yang hendak dianalisis. Terkadang dalam beberapa kasus, seseorang hanya tertarik bab tertentu dari suatu image. Dengan kata lain, bab lainnya diabaikan dan tidak dianalisis. Langsung saja berikut script untuk masking.
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('image.jpg',0)
# Create a mask
mask = np.zeros(img.shape[:2], np.uint8)
mask[100:300, 100:400] = 255
masked_img = cv2.bitwise_and(img,img,mask = mask)
# Calculate histogram with mask and without mask
# Check third argument for mask
hist_full = cv2.calcHist([img],[0],None,[256],[0,256])
hist_mask = cv2.calcHist([img],[0],mask,[256],[0,256])
plt.subplot(221), plt.imshow(img, 'gray')
plt.title('Full Image')
plt.subplot(222), plt.imshow(mask,'gray')
plt.title('Mask')
plt.subplot(223), plt.imshow(masked_img, 'gray')
plt.title('Masked')
plt.subplot(224), plt.plot(hist_full), plt.plot(hist_mask)
plt.legend(('Full','Masked'), loc = 'upper right')
plt.title('Histogram')
plt.xlim([0,256])
plt.show()

Berikut hasilnya.


Bagian pertama selesai, lanjut ke bab selanjutnya.
Sumber http://lang8088.blogspot.com

Senin, 30 Juli 2018

Programming Python Fibonacci Numbers

The Fibonacci sequence is named after Italian mathematician Leonardo of Pisa, known as Fibonacci. His 1202 book Liber Abaci introduced the sequence to Western European mathematics, although the sequence had been described earlier as Virahanka numbers in Indian mathematics.

The Fibonacci sequence is named after Italian mathematician Leonardo of Pisa Programming Python Fibonacci Numbers


By modern convention, the sequence begins either with F0 = 0 or with F1 = 1.
The next number is found by adding up the two numbers before it.
The 2 is found by adding the two numbers before it (1 + 1), similarly, the 3 is found by adding the two numbers before it (1 + 2), next the 5 is (2+3), and so on.

Example: the next number in the sequence above is 21 + 34 = 55

It is that simple, and here is a longer list:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, ...

The Fibonacci sequence is named after Italian mathematician Leonardo of Pisa Programming Python Fibonacci Numbers


Here is the source code for Fibonacci sequence.

#Python
#Program fibonacci Loki Lang
print 'Masukkan suatu nilai:'
num = int(input())
if num < 0:
    num *= -1
    a, b = 0, -1
    for i in range(num):
        a, b = b, a - b
        print 'Bilangan fibonacci', (i + 1) * -1, 'ialah', a
    num *= -1
else:
    a, b = 0, 1
    for i in range(num):
        a, b = b, a + b
        print 'Bilangan fibonacci', i + 1, 'ialah', a
print 'Nilai fibonacci', num ,'ialah', a

Sumber http://lang8088.blogspot.com

Minggu, 29 Juli 2018

Programming Python Euclid’S Algorithm For Finding The Gcd Of Two Numbers

Greatest Common Divisor
In mathematics, the greatest common divisor of two or more integers, when at least one of them is not zero, is the largest positive integer that divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4. The greatest common divisor is also known as the greatest common factor (gcf), highest common factor (hcf), greatest common measure (gcm), or highest common divisor.

 the greatest common divisor of two or more integers Programming Python Euclid’s Algorithm for Finding the GCD of Two Numbers


Factors are the numbers that can be multiplied to produce a particular number. Just look at this simple multiplication:

4 × 6 = 24

In the above math problem, 4 and 6 are factors of 24. Another name for factor is divisor. The number 24 also has some other factors such as:

8 × 3 = 24
12 × 2 = 24
24 × 1 = 24

From the above three math problems, 8 and 3 are also factors of 24, as are 12 and 2, and 24 and 1. So the factors of 24 are: 1, 2, 3, 4, 6, 8, 12, and 24. Next, let’s look at the factors of 30:

1 × 30 = 30
2 × 15 = 30
3 × 10 = 30
5 × 6 = 30

So the factors of 30 are 1, 2, 3, 5, 6, 10, 15, and 30. Notice that any number will always have 1 and itself as factors. From the list of factors for 24 and 30, there are factors that 24 and 30 have in common, 1, 2, 3, and 6. The greatest number of these is 6. So 6 is the greatest common factor or, more commonly, the greatest common divisor of 24 and 30.

Euclid’s Algorithm for Finding the GCD of Two Numbers
A mathematician who lived 2,000 years ago named Euclid came up with an algorithm for finding the greatest common divisor of two numbers.
In mathematics, the Euclidean algorithm, or Euclid's algorithm, is an efficient method for computing the greatest common divisor (GCD) of two numbers, the largest number that divides both of them without leaving a remainder. It is named after the ancient Greek mathematician Euclid, who first described it in Euclid's Elements (c. 300 BC). It is an example of an algorithm, a step-by-step procedure for performing a calculation according to well-defined rules, and is one of the oldest algorithms in common use. It can be used to reduce fractions to their simplest form, and is a part of many other number-theoretic and cryptographic calculations.
The Euclidean algorithm is based on the principle that the greatest common divisor of two numbers does not change if the larger number is replaced by its difference with the smaller number. For example, 21 is the GCD of 252 and 105 (252 = 21 × 12 and 105 = 21 × 5), and the same number 21 is also the GCD of 105 and 147 = 252 − 105. Since this replacement reduces the larger of the two numbers, repeating this process gives successively smaller pairs of numbers until one of the two numbers reaches zero. When that occurs, the other number (the one that is not zero) is the GCD of the original two numbers. By reversing the steps, the GCD can be expressed as a sum of the two original numbers each multiplied by a positive or negative integer, e.g., 21 = 5 × 105 + (−2) × 252. The fact that the GCD can always be expressed in this way is known as Bézout's identity.
The version of the Euclidean algorithm described above (and by Euclid) can take many subtraction steps to find the GCD when one of the given numbers is much bigger than the other. A more efficient version of the algorithm shortcuts these steps, instead replacing the larger of the two numbers by its remainder when divided by the smaller of the two. With this improvement, the algorithm never requires more steps than five times the number of digits (base 10) of the smaller integer. This was proven by Gabriel Lamé in 1844, and marks the beginning of computational complexity theory. Additional methods for improving the algorithm's efficiency were developed in the 20th century.
The Euclidean algorithm has many theoretical and practical applications. It is used for reducing fractions to their simplest form and for performing division in modular arithmetic. Computations using this algorithm form part of the cryptographic protocols that are used to secure internet communications, and in methods for breaking these cryptosystems by factoring large composite numbers. The Euclidean algorithm may be used to solve Diophantine equations, such as finding numbers that satisfy multiple congruences according to the Chinese remainder theorem, to construct continued fractions, and to find accurate rational approximations to real numbers. Finally, it is a basic tool for proving theorems in number theory such as Lagrange's four-square theorem and the uniqueness of prime factorizations. The original algorithm was described only for natural numbers and geometric lengths (real numbers), but the algorithm was generalized in the 19th century to other types of numbers, such as Gaussian integers and polynomials of one variable. This led to modern abstract algebraic notions such as Euclidean domains.
Euclid’s GCD algorithm is short. Here’s a source code kegiatan that implements his algorithm as Python code.

#Python source code untuk mencari Faktor Persekutuan Terbesar
#Loki Lang

def main():
    first = int(input("Masukkan bilangan pertama "))
    second = int(input("Masukkan bilangan kedua "))
    result = gcd(first, second)
    print("Faktor komplotan terbesar dari %s dan %s yakni %s" %(first, second, result))

def gcd(a, b):
    while a != 0:
        a, b = b % a, a
    return b

if __name__ == '__main__':
    main()



Sumber http://lang8088.blogspot.com

Senin, 23 Juli 2018

Belajar String Python Sederhana

Program ini memakai Python versi 2. Script Python sanggup ditulis di text editor semisal Notepad dan simpan dengan extension .py.

 Script Python sanggup ditulis di text editor semisal Notepad dan simpan dengan extension  Belajar String Python Sederhana


Berikut ialah script pertama yang digunakan.

#Python
#Program Hello World Loki Lang
print 'Hello World'
print 'Ketik string:'
myString = raw_input()
print 'String:',myString
print 'Upper:', myString.upper()
print 'Lower:', myString.lower()
print 'Capitalize:', myString.capitalize()
print 'Title:', myString.title()
lenght = len(myString)
print 'Panjang dari', myString, 'ialah', lenght, 'character'


Dalam pemrograman komputer, string ialah sebuah deret simbol. Tipe data string ialah tipe data yang dipakai untuk menyimpan barisan karakter, tipe data char.
  • Komentar dalam Python memakai '#', kalimat dalam satu baris dan berada di belakang tanda '#' tidak dihukum dalam program, hanya sebatas komentar
  • Function print, dipakai untuk mencetak pesan nilai dari suatu constanta atau variable.
    Function raw_input(), dipakai untuk mendapatkan input dari user, tipe data secara default ialah string
  • Method string, upper(), dipakai untuk mengolah suatu string, dan mengembalikannya dalam bentuk uppercase, lebih jelasnya lihat bab hasil
  • Method string, lower(), dipakai untuk mengolah suatu string, dan mengembalikannya dalam bentuk lowercase, lebih jelasnya lihat bab hasil
  • Method string, capitalize(), dipakai untuk mengolah suatu string, dan mengembalikannya dalam bentuk capitalize, lebih jelasnya lihat bab hasil
  • Method string, title(), dipakai untuk mengolah suatu string, dan mengembalikannya dalam bentuk title, lebih jelasnya lihat bab hasil
  • Function len(), dipakai untuk mencacah jumlah character dari suatu string, return value berupa tipe data integer

Contoh tampilan hasil script pertama tersebut ialah sebagai berikut.

>>>
Hello World
Ketik string:
Manchester united
String: Manchester united
Upper: MANCHESTER UNITED
Lower: manchester united
Capitalize: Manchester united
Title: Manchester United
Panjang dari Manchester united ialah 17 character
>>>


Script kedua yang digunakan.

#Python
#String dan Index Loki Lang
myString = raw_input('Masukkan sebuah string ')
INTJ = len(myString)
for i in range(INTJ):
    print 'Index', i, 'dari', myString, 'adalah', myString[i]
print ''
for i in range(INTJ):
    l = -1*INTJ+i
    print 'Index', l, 'dari', myString, 'adalah', myString[l]


Seperti dijelaskan sebelumnya bahwa tipe data string merupakan formasi simbol. Setiap character simbol tersebut menempati index tertentu dari string tersebut, menyerupai terlihat di pola hasil script.
Index deret character tersebut dimulai dari 0 sampai index n-1, dimana n ialah jumlah character keseluruhan. Satu hal yang menarik dari string di Python ialah index negatif, yang mana index -n ialah merujuk pada character yang sama dengan index 0, dan index -1 ialah merujuk pada character yang sama dengan index n-1.

>>>
Masukkan sebuah string Loki Lang
Index 0 dari Loki Lang ialah L
Index 1 dari Loki Lang ialah o
Index 2 dari Loki Lang ialah k
Index 3 dari Loki Lang ialah i
Index 4 dari Loki Lang ialah
Index 5 dari Loki Lang ialah L
Index 6 dari Loki Lang ialah a
Index 7 dari Loki Lang ialah n
Index 8 dari Loki Lang ialah g

Index -9 dari Loki Lang ialah L
Index -8 dari Loki Lang ialah o
Index -7 dari Loki Lang ialah k
Index -6 dari Loki Lang ialah i
Index -5 dari Loki Lang ialah
Index -4 dari Loki Lang ialah L
Index -3 dari Loki Lang ialah a
Index -2 dari Loki Lang ialah n
Index -1 dari Loki Lang ialah g
>>>



Sumber http://lang8088.blogspot.com

Minggu, 22 Juli 2018

Belajar Python Penggabungan Dan Perulangan String

Salah satu keunikkan Python yaitu feature penggabungan dan perulangan string yang begitu sederhana. Suatu string sanggup digabungkan dengan string lainnya. Akan tetapi perlu diingat bahwa tipe data string tidak sanggup digabungkan dengan tipe data integer maupun float. Penggabungan beberapa string sanggup dilakukan dengan memakai operator '+'. Berikut referensi syntax sederhananya.

output = input1 + input2


Dimana input1 dan input2 yaitu dua buah string yang akan digabungkan, sedangkan output yaitu string hasil penggabungannya.

Salah satu keunikkan Python yaitu feature penggabungan dan perulangan string yang begitu  Belajar Python Penggabungan dan Perulangan String


Selain penggabungan, perulangan string pada Python relatif begitu sederhana dan gampang dipahami. Dengan memakai operator '*' sebagai perulangan dan n, jumlah perulangannya. Contoh perulangan string sebanyak 3 kali.

output = input * 3


String pada variable input diulang sebanyak 3 kali dan disimpan pada variable output.
sebagai perbandingan antara C++ dengan Python, berikut ini dua buah source code untuk mendapat hasil output yang sama.

Source Code C++ Pertama

#include <iostream>
using namespace std;
int main()
{
    int l,m,n;
    cout<<"Masukkan jumlah baris ";
    cin>>l;
    for (m=0; m<l; m++)
    {
        for (n=0; n<=m; n++)
        {
            cout<<"*";
        }
        cout<<endl;
    }
    return 0;
}


Script Python Pertama

INTJ = input('Masukkan jumlah baris ')
for i in range(INTJ):
    print '*'*(i+1)


Hasil Pertama

>>>
Masukkan jumlah baris 5
*
**
***
****
*****
>>>


Source Code C++ Kedua

#include <iostream>
using namespace std;
void error();
int main()
{
    int l,m,n,o,p;
    cout<<"Masukkan jumlah baris bintang: ";
    cin>>l;
    if(l<1)
    error();
    else
    p=l;
    for(m=1;m<=l;m++)
    {
        for(n=p;n>=1;n--)
        {
            if(n>1)
            cout<<" ";
        }
        for(o=1;o<=m;o++)
        {
            cout<<"*";
        }
        p-=1;
        cout<<endl;
    }
    return 0;
}


Script Python Kedua

INTJ = input('Masukkan jumlah baris ')
for i in range(INTJ):
    j = i+1
    print ' '*(INTJ-j)+'*'*j


Hasil Kedua

>>>
Masukkan jumlah baris 5
    *
   **
  ***
 ****
*****
>>>


Source Code C++ Ketiga

#include <iostream>
using namespace std;
int main()
{
    int l,m,n,o,p;
    cout<<"Masukkan tinggi pyramid ";
    cin>>l;
    p=l;
    for(m=1;m<=l;m++)
    {
        for(n=p;n>=1;n--)
        {
            if(n>1)
            cout<<" ";
        }
        for(o=1;o<=2*m-1;o++)
        {
            cout<<"*";
        }
        p-=1;
        cout<<endl;
    }
    return 0;
}


Script Python Ketiga

INTJ = input('Masukkan tinggi pyramid ')
for i in range(INTJ):
    j = i+1
    print ' '*(INTJ-j)+('*'*(2*j-1))


Hasil Ketiga

>>>
Masukkan tinggi pyramid 5
    *
   ***
  *****
 *******
*********
>>>


Untuk source code C++ secara explicit memakai nested for loops, perulangan bersarang. Sementara script Python nested loops secara implicit, maksudnya dalam script tersebut hanya memakai satu buah perulangan for, namun di dalamnya terdapat operator '*' untuk perulangan string. Antara C++ dengan Python, dengan hasil yang sama pada source code tersebut, Python lebih sederhana dan singkat dibandingkan C++.
Sumber http://lang8088.blogspot.com

Jumat, 20 Juli 2018

Belajar Python Dasar Integer Dan Float

Integer
Pada Python, secara default input() dari user akan dianggap sebagai suatu tipe data integer atau bilangan bulat.

 dari user akan dianggap sebagai suatu tipe data integer atau bilangan lingkaran Belajar Python Dasar Integer dan Float


Oleh alasannya itu kalau input() diberikan suatu nilai masukkan selain angka (sesuai ASCCI), maka akan didapati error sanksi program.
Berikut teladan script untuk memahami tipe data integer.

INTJ = input('Masukkan angka lingkaran pertama ')
INTP = input('Masukkan angka lingkaran kedua ')
print 'Penjumlahan', INTJ, 'ditambah', INTP, '=', INTJ+INTP
print 'Pengurangan', INTJ, 'dikurangi', INTP, '=', INTJ-INTP
print 'Perkalian', INTJ, 'dikali', INTP, '=', INTJ*INTP
print 'Pembagian', INTJ, 'dibagi', INTP, '=', INTJ/INTP


Berikut teladan sanksi program.



Bila diperhatikan ada yang asing pada hasil pembagian dua buah bilangan lingkaran tersebut. Bila mengacu pada pembagian Matematika, seharusnya 7 dibagi 8 yaitu 0,875. Namun, pada hasil sanksi aktivitas tersebut 7 dibagi 8, karenanya yaitu 0. Penjelasan untuk hal tersebut yaitu sebagai berikut.
Hasil pembagian yang dilakukan dua buah bilangan integer hanya akan menghasilkan kondisi berapa nilai bilangan lingkaran yang habis terbagi. Contoh saat 7 dibagi 8 hasil pembagian 0, dengan sisa yang tidak sanggup terbagi lingkaran yaitu 7, sehingga output pembagian 7 dibagi 8 yaitu 0. Contoh lain:
  • 27 / 5 = 5 sisa 2, output = 5
  • 36 / 9 = 4 sisa 0, output = 4
  • 46 / 4 = 11 sisa 2, output = 11

Operasi Matematika yang meliputi beberapa tipe data integer, akan menghasilkan output tipe data integer juga.

Float
Secara sederhana tipe data float yaitu tipe data yang dipakai untuk bilangan pecahan. Berikut ini yaitu script untuk membandingkan hasil operasi Matematika antara integer dengan float.

INTJ = input('Masukkan sebuah angka ')
FLOAT = float(INTJ)
print 'Penjumlahan', INTJ, '+ 100 =', INTJ+100
print 'Penjumlahan', INTJ, '+ 100.0 =', INTJ+100.0
print 'Penjumlahan', FLOAT, '+ 100 =', FLOAT+100
print 'Penjumlahan', FLOAT, '+ 100.0 =', FLOAT+100.0
print 'Pengurangan', INTJ, '- 100 =', INTJ-100
print 'Pengurangan', INTJ, '- 100.0 =', INTJ-100.0
print 'Pengurangan', FLOAT, '- 100 =', FLOAT-100
print 'Pengurangan', FLOAT, '- 100.0 =', FLOAT-100.0
print 'Perkalian', INTJ, '* 100 =', INTJ*100
print 'Perkalian', INTJ, '* 100.0 =', INTJ*100.0
print 'Perkalian', FLOAT, '* 100 =', FLOAT*100
print 'Perkalian', FLOAT, '* 100.0 =', FLOAT*100.0
print 'Pembagian', INTJ, '/ 100 =', INTJ/100
print 'Pembagian', INTJ, '/ 100.0 =', INTJ/100.0
print 'Pembagian', FLOAT, '/ 100 =', FLOAT/100
print 'Pembagian', FLOAT, '/ 100.0 =', FLOAT/100.0
print 'Sisa', INTJ, '% 100 =', INTJ%100
print 'Sisa', INTJ, '% 100.0 =', INTJ%100.0
print 'Sisa', FLOAT, '% 100 =', FLOAT%100
print 'Sisa', FLOAT, '% 100.0 =', FLOAT%100.0


Berikut hasil sanksi programnya.



Operasi Matematika yang melibatkan tipe data float dengan integer, akan menghasilkan output tipe data float.

Integer to Float
Untuk mengubah tipe data dari integer menjadi float, yaitu dengan memakai float. Berikut ini yaitu teladan script.

INTJ = input('Masukkan bilangan lingkaran pertama ')
INTP = input('Masukkan bilangan lingkaran kedua ')
print 'INTJ =', INTJ
print 'INTP =', INTP
FLOAT1 = float(INTJ/INTP)
FLOAT2 = float(INTJ)
FLOAT3 = float(INTP)
FLOAT4 = FLOAT2/FLOAT3
print 'INTJ/INTP = ', INTJ/INTP
print 'float(INTJ/INTP) =', FLOAT1
print 'float(INTJ) / float(INTP) = ', FLOAT2, '/', FLOAT3, '=', FLOAT4


Berikut hasil eksekusinya.



Perlu diperhatikan bahwa hasil dari float(INTJ/INTP) dengan float(INTJ) / float(INTP), tidaklah sama. Untuk float(INTJ/INTP), dua buah nilai integer tersebut dilakukan operasi pembagian terlebih dahulu, sehingga output pembagiannya yaitu integer. Nilai output pembagian integer tersebut, barulah diubah menjadi float, sehingga nilainya menyerupai yang ada pada teladan dan klarifikasi sebelumnya.
Sedangkan untuk float(INTJ) / float(INTP), masing-masing tipe data integer tersebut diubah terlebih dahulu menjadi float. Barulah sesudah keduanya menjadi float, dilakukan proses pembagian.
Sumber http://lang8088.blogspot.com