Python brojevi, pretvorba tipova i matematika

U ovom ćete članku naučiti o različitim brojevima koji se koriste u Pythonu, kako pretvoriti iz jednog tipa podataka u drugi i matematičkim operacijama koje podržava Python.

Brojčani tip podataka u Pythonu

Python podržava cijele brojeve, brojeve s pomičnom zarezom i složene brojeve. Oni su definirani kao int, floati complexklase u Pythonu.

Cijeli brojevi i pomične točke razdvajaju se prisutnošću ili odsutnošću decimalne točke. Na primjer, 5 je cijeli broj, dok je 5.0 broj s pomičnom zarezom.

Kompleksni brojevi zapisani su u obliku, x + yjgdje je x stvarni dio, a y imaginarni dio.

Pomoću type()funkcije možemo znati kojoj klasi pripada varijabla ili vrijednost i isinstance()funkcijom provjeriti pripada li određenoj klasi.

Pogledajmo primjer:

 a = 5 print(type(a)) print(type(5.0)) c = 5 + 3j print(c + 3) print(isinstance(c, complex))

Kada pokrenemo gornji program, dobit ćemo sljedeći izlaz:

 (8 + 3j) Istina

Iako cijeli brojevi mogu biti bilo koje duljine, broj s pomičnim zarezom precizan je samo do 15 decimalnih mjesta (16. mjesto je netočno).

Brojevi s kojima se svakodnevno bavimo decimalnim su brojevima (baza 10). Ali računalni programeri (obično ugrađeni programeri) moraju raditi s binarnim (baza 2), heksadecimalnim (baza 16) i osminskim (baza 8) brojevnim sustavima.

U Pythonu te brojeve možemo predstaviti odgovarajućim prefiksom ispred tog broja. Sljedeća tablica navodi ove prefikse.

Brojevni sustav Prefiks
Binarni "0b" ili "0B"
Oktalni '0o' ili '0O'
Heksadecimalni "0x" ili "0X"

Evo nekoliko primjera

 # Output: 107 print(0b1101011) # Output: 253 (251 + 2) print(0xFB + 0b10) # Output: 13 print(0o15)

Kada pokrenete program, izlaz će biti:

 107 253 13

Pretvorba tipa

Možemo pretvoriti jednu vrstu broja u drugu. To je također poznato kao prisila.

Operacije poput zbrajanja, oduzimanja prisiljavaju cijeli broj da implicitno pluta (automatski), ako je jedan od operanda float.

 >>> 1 + 2.0 3.0

Gore možemo vidjeti da je 1 (cijeli broj) prisiljen u 1.0 (plutajući) za zbrajanje, a rezultat je također broj s pomičnom zarezom.

Mi također mogu koristiti ugrađene funkcije kao što su int(), float()i complex()pretvoriti između tipova eksplicitno. Te se funkcije mogu čak pretvoriti iz niza.

 >>> int(2.3) 2 >>> int(-2.8) -2 >>> float(5) 5.0 >>> complex('3+5j') (3+5j)

Prilikom pretvaranja iz plutajućeg u cijeli broj, broj se skraćuje (decimalni dijelovi se uklanjaju).

Python decimalni

Python ugrađeni float klase izvodi neke izračune koji bi nas mogli zapanjiti. Svi znamo da je zbroj 1.1 i 2.2 3.3, ali čini se da se Python ne slaže.

 >>> (1.1 + 2.2) == 3.3 False

Što se događa?

Ispada da se brojevi s pomičnom zarezom implementiraju u računalni hardver kao binarni razlomci jer računalo razumije samo binarne (0 i 1). Iz tog razloga, većina decimalnih razlomaka koje poznajemo, ne može se točno pohraniti u naše računalo.

Uzmimo primjer. Razlomak 1/3 ne možemo prikazati kao decimalni broj. To će dati 0,33333333 … što je beskrajno dugo, a mi ga možemo samo približiti.

It turns out that the decimal fraction 0.1 will result in an infinitely long binary fraction of 0.000110011001100110011… and our computer only stores a finite number of it.

This will only approximate 0.1 but never be equal. Hence, it is the limitation of our computer hardware and not an error in Python.

 >>> 1.1 + 2.2 3.3000000000000003

To overcome this issue, we can use the decimal module that comes with Python. While floating-point numbers have precision up to 15 decimal places, the decimal module has user-settable precision.

Let's see the difference:

 import decimal print(0.1) print(decimal.Decimal(0.1))

Output

 0.1 0.1000000000000000055511151231257827021181583404541015625

This module is used when we want to carry out decimal calculations as we learned in school.

It also preserves significance. We know 25.50 kg is more accurate than 25.5 kg as it has two significant decimal places compared to one.

 from decimal import Decimal as D print(D('1.1') + D('2.2')) print(D('1.2') * D('2.50'))

Output

 3.3 3.000

Notice the trailing zeroes in the above example.

We might ask, why not implement Decimal every time, instead of float? The main reason is efficiency. Floating point operations are carried out must faster than Decimal operations.

When to use Decimal instead of float?

We generally use Decimal in the following cases.

  • When we are making financial applications that need exact decimal representation.
  • When we want to control the level of precision required.
  • When we want to implement the notion of significant decimal places.

Python Fractions

Python provides operations involving fractional numbers through its fractions module.

A fraction has a numerator and a denominator, both of which are integers. This module has support for rational number arithmetic.

We can create Fraction objects in various ways. Let's have a look at them.

 import fractions print(fractions.Fraction(1.5)) print(fractions.Fraction(5)) print(fractions.Fraction(1,3))

Output

 3/2 5 1/3

While creating Fraction from float, we might get some unusual results. This is due to the imperfect binary floating point number representation as discussed in the previous section.

Fortunately, Fraction allows us to instantiate with string as well. This is the preferred option when using decimal numbers.

 import fractions # As float # Output: 2476979795053773/2251799813685248 print(fractions.Fraction(1.1)) # As string # Output: 11/10 print(fractions.Fraction('1.1'))

Output

 2476979795053773/2251799813685248 11/10

This data type supports all basic operations. Here are a few examples.

 from fractions import Fraction as F print(F(1, 3) + F(1, 3)) print(1 / F(5, 6)) print(F(-3, 10)> 0) print(F(-3, 10) < 0)

Output

 2/3 6/5 False True

Python Mathematics

Python offers modules like math and random to carry out different mathematics like trigonometry, logarithms, probability and statistics, etc.

 import math print(math.pi) print(math.cos(math.pi)) print(math.exp(10)) print(math.log10(1000)) print(math.sinh(1)) print(math.factorial(6))

Output

 3.141592653589793 -1.0 22026.465794806718 3.0 1.1752011936438014 720

Here is the full list of functions and attributes available in the Python math module.

 import random print(random.randrange(10, 20)) x = ('a', 'b', 'c', 'd', 'e') # Get random choice print(random.choice(x)) # Shuffle x random.shuffle(x) # Print the shuffled x print(x) # Print random element print(random.random())

Kada pokrenemo gornji program, dobivamo izlaz na sljedeći način (vrijednosti se mogu razlikovati zbog slučajnog ponašanja)

 18 e ('c', 'e', ​​'d', 'b', 'a') 0,5682821194654443

Evo punog popisa funkcija i atributa dostupnih u slučajnom modulu Python.

Zanimljivi članci...