How to use the basic mathematical calculation in Python programming

Source: Internet
Author: User
Tags integer division
This article mainly introduces the basic mathematical calculations used in Python programming, which focuses on the use of division operations and related pision modules, the need for friends can refer to the following

Number
In Python, the logarithm of the rules is relatively simple, basic mathematics at the primary level can be understood.

So, as a zero-basis to learn this, but also from the calculation of primary math problems began. Because starting from here, the basic knowledge of mathematics yours faithfully certainly pass.


>>> 33>>> 33333333333333333333333333333333333333333333333333333333333333333333333333333333L >>> 3.2222223.222222


The above is shown in interactive mode, if you enter 3, it shows 3, such a number is called an integer, this address is the same as primary math.

If you enter a larger number, the second, then multiple 3 is an integer, called a long integer in Python. To indicate that a number is a long integer, Python displays an L at the end of it. In fact, Python now has the ability to automatically treat a large number of inputs as long integers. You don't have to make a difference in this respect.

Third, it's called a decimal in math, you can still call it that, but like many programming languages, it's customary to call it "floating point." As for the name of the origin, is also a little said, is interested in Google.

In the above example, it can be said to be unsigned (or non-negative), if you want to represent negative numbers, as in the mathematical representation of the same way, preceded by the minus sign.

It is important to note that we are talking about decimal numbers here.

In addition to the decimal, there are binary, octal, hexadecimal are in the programming may be used, of course, with 60 of the time is relatively small (in fact, the time is recorded in the typical six decimal).

Each number, in Python, is an object, such as the previous input 3, which is an object. Each object has its own address in memory, and this is its identity.


>>> ID (3) 140574872>>> ID (3.222222) 140612356>>> ID (3.0) 140612356>>>


Use the built-in function ID () to view the memory address, or identity, of each object.

Built-in functions, the English built-in function, the reader can also guess according to the name of a sorta. Yes, it is an intrinsic function already defined in Python.
The above three different numbers are three different objects with three different memory addresses. In particular, it is important to note that in mathematics, 3 and 3.0 are equal, but here, they are different objects.

The memory address obtained with ID () is read-only and cannot be modified.

Knowing "identity" and then "type", there is also a built-in function for using type ().


>>> type (3) <type ' int ' >>>> type (3.0) <type ' float ' >>>> type (3.222222) <type ' Float ' >


Use the built-in function to see the type of the object. <type ' int ', description 3 is an integer type (interger); <type ' float ' > tells us that the object is a floating-point type (floating, a real number). Similar to the result of ID (), the result of type () is also read-only.

As for the value of the object, here is the object itself.

It seems that the object is not difficult to understand. Please remain confident and continue.

Variable
Just writing 3, 4, and 5 is not enough, in programming languages, it is often used to establish a correspondence between "variable" and "number" (Strictly speaking object in Python). For example:


>>> x = 5>>> x5>>> x = 6>>> x6


In this example, X = 5 is the corresponding relationship between the variable (x) and the (5), and then the corresponding relationship between X and 6 is established. We can see that x first "is" 5, then "yes" 6.

In Python, it is important to have such a sentence: The object has a type, and the variable has no type. How do you understand it?

First of all, 5, 6 are integers, Python takes a name for them, called "integer" type of data, or the data type is an integer, denoted by an int.

When we write in Python 5, 6,computer girl automatically in her memory somewhere to set up these two objects (the definition of the object will say, here you first use, gradually clear meaning), like the construction of two sculptures, one is shaped like 5, a shape like 6, which is two objects, the type of these two objects is int.

What about the X? Is like a label, when x = 5 o'clock, is the X this label is tied to 5, through this x, it is postponed to see 5, so in the interactive mode,>>> x output is 5, the feeling seems to be X is 5, the fact is x this label affixed to 5 above. In the same way, when x = 6 o'clock, the label will change position and stick to 6.

So, this tag x has no type, it can not only be affixed to an integer type of object, but also can be affixed to other types of objects, such as the following will be introduced to the STR (string) type of objects and so on.

This is a very important place for Python to differentiate itself from some languages.

Arithmetic
According to the following requirements, run in interactive mode to see if the results are consistent with the results obtained from the mathematical knowledge of primary school


>>> 2+57>>> 5-23>>> 10/25>>> 5*210>>> 10/5+13>>> 2*3-42


In the above operation, four arithmetic symbols are involved: plus (+), minus (-), multiply (*), divide (/)

In addition, I believe crossing has found an important axiom:

In the computer, arithmetic and elementary mathematics have learned the same arithmetic rules.

Otherwise, people are higher animals, their own inventions, must inherit the knowledge that they have mastered, do not go against their own history. The great scientists, in the original design of the computer when the thought of yours faithfully now learning needs, must not let future generations to learn the new rules of operation, using primary mathematics inside the good. Thanks to the pioneers of the scientists, Ze is hereafter.

Three arithmetic questions are calculated below to see what the results are


4 + 24.0 + 24.0 + 2.0


Crossing may be angry, such a simple topic, do not excuse the computer, too wasted.

Do not worry, or to calculate, and then see the results, there is no different? Take a closer look at OH.


>>> 4+26>>> 4.0+26.0>>> 4.0+2.06.0


The difference is that the first result is 6, which is an integer, followed by two is 6.0, which is a floating-point number.

Definition 1: Numbers such as 4,-2, 129486655, 988654, 0 are called integers
Definition 2: Numbers such as 4.0,-2.0, 2344.123, 3.1415926 are called floating-point numbers
The definition of these two, do not memorize, Google a bit. Remember what Einstein said: "I don't remember any of the books." It seems to be, probably mean, I don't remember anyway. He didn't say, I added: Forget about Google.

It seems that computers do some arithmetic, but there is one problem you must be aware of: in mathematics, integers can be infinitely large, but in computers, integers cannot be infinitely large. Why is it? (I recommend you to Google, in fact, the basic knowledge of computers must have studied.) Therefore, there will be a situation, that is, the number of participating in the operation or the result of more than the maximum number of computers, this problem is called "integer overflow problem."

Integer overflow problem
Here is an article devoted to this issue, recommended reading: integer overflow

For other languages, integer overflow is a must, but, in Python, crossing is not sad, because Python solves this problem for us, please read the following: large integer multiplication

Ok! crossing can experiment with large integer multiplication in the IDE.


>>> 123456789870987654321122343445567678890098876* 1233455667789990099876543332387665443345566152278477193527562870044352587576277277562328362032444339019158937017801601677 976183816L


Crossing is lucky, Python is sad, so the choice to learn Python is to cherish the time.

The number at the end of the calculated result has an L, which means that the number is a long integer, but crossing does not care about this, but Python has done it for us anyway.

Before closing this section, there are two symbols that need to be crossing in mind (do not remember or do not mind, can at any time Google, just remember to use more convenient)

Integer, expressed in int, from Word: integer
Floating-point number, expressed in float, is the word: float
You can use a command: Type (object) to detect what type a number is.


>>> type (4) <type ' int ' >  #4 is int, integer >>> type (5.0) <type ' float ' > #5.0 is float, floating-point number type ( 988776544222112233445566778899887766554433221133344455566677788998776543222344556678) <type ' Long ' >  # is a long integer and is also an integer


Division
The division is verbose, not just Python.

Integer divided by integer
After entering Python interaction mode (later in this tutorial, you may no longer repeat this kind of narration, just see >>>, as shown in interactive mode), practice the following:

>>> 2/50>>> 2.0/50.4>>> 2/5.00.4>>> 2.0/5.00.4


Do you see it? Trouble out (this is in python2.x), according to the mathematical operation, the above four operation results should be 0.4. But we see the following three matches, and the first one actually turns out to be 0. Why?

Because, in Python (Strictly python2.x, Python3 will change) there is a rule, like the division in 2/5, is to take the whole (that is, to remove the decimal, but not rounding). 2 divided by 5, quotient is 0 (integer), remainder is 2 (integer). So if you use this form: 2/5, the result is the quotient of that integer. Or it can be understood that an integer divided by an integer results in an integer (quotient).

Like what:

>>> 5/22>>> 7/23>>> 8/24


Note: Get the quotient (integer) instead of getting the result that contains the decimal digits and then rounding it up. For example: 5/2, the obtained is quotient 2, the remainder 1, and finally 5/2 = 2. The 2.5 is not rounded.

Dividing floating-point numbers with integers
This title is not the same as the title above, the title is "Integer divided by integers", if the style consistent requirements, this section title should be "floating number divided by integer", but no, now is "floating point number and integer division", which means:

Suppose: x divided by Y. where x may be an integer or a floating-point number, y may be an integer, or it may be a floating-point number.
Before concluding, do the experiment first:

>>> 9.0/24.5>>> 9/2.04.5>>> 9.0/2.04.5>>> 8.0/24.0>>> 8/2.04.0>& Gt;> 8.0/2.04.0


Induction, get the rule: whether the divisor or divisor, as long as there is a number is a floating point, the result is a floating point. So, if the result of the division is the remainder, it will not be the same as before, but to return a floating-point number, which is the same as the result of learning mathematically.


>>> 10.0/33.3333333333333335


This is not a bit funny, according to mathematical knowledge, it should be 3.33333 ..., followed by the 3 cycle. Then your computer will not stop, full screen is 3. To avoid this, Python arbitrarily ended the loop, but sadly did not terminate with the "rounding" principle. Of course, there will be more wonderful appearance:


>>> 0.1 + 0.20.30000000000000004>>> 0.1 + 0.1-0.20.0>>> 0.1 + 0.1 + 0.1-0.35.55111512312578 3e-17>>> 0.1 + 0.1 + 0.1-0.20.10000000000000003


More and more confused, why computer girl in the calculation of such a simple problem, so confused? Not computer girl is confused, she still clever. The reason is that the decimal and binary conversion, computer girl with the binary for the calculation, the above example, we enter the decimal, she will convert the decimal number into binary, and then calculate. However, in the conversion, the floating point number into the binary, there is a problem.

For example, decimal 0.1, converted to binary is: 0.0001100110011001100110011001100110011001100110011 ...

That is, after conversion to binary, it is not exactly equal to 0.1 of the decimal. At the same time, the number of bits stored in the computer is limited, so the above phenomenon occurs.

This problem is not just python, all programming languages that support floating-point arithmetic are encountered, and it is not a python bug.

Understand the cause of the problem, how to solve it? As far as Python's floating-point arithmetic is concerned, the error on most machines does not exceed one of 2**53 points per calculation. This is enough for most tasks, but keep in mind that this is not a decimal algorithm, and each floating-point calculation may introduce a new rounding error.

In general, the desired end result is obtained simply by "rounding" the results of the final display to the desired decimal digits.

For situations that need to be very precise, you can use the decimal module, which is implemented to fit the application of accounting and high-precision requirements. Another form of operation is supported by the fractions module, which implements operations based on rational numbers (so that numbers like 1/3 can be accurately represented). The highest requirement is to use the numerical Python package provided by SciPy and other packages for math and statistics. Listing these things simply allows crossing to understand that there are a number of ways to solve the problem, which will be solved in some way later.

I have a link recommended to you for the infinite loop decimal problem, it's not as simple as it might seem. READ: Wikipedia entry: 0.999 ..., will you have a deep understanding of it?

Add a profile for interested friends to read: floating point algorithm: disputes and limitations
Python will always provide a variety of solutions to the problem, which is her style.

Reference module solve division--Enable wheels
One of the most important reasons for Python's popularity is that there are many wheels. It's a metaphor. It's like you're running fast, what do you do? The light practice running every day is no drop, to use the wheel. It's a lot quicker to find a bike. Not too fast enough to change the battery, then change the car, and then change the high-speed rail ... You can choose a lot anyway. But most of the things that make you run fast are not made by yourself, they are made by others, and you use them. Even two legs thanks to parents for their gifts. Because of the many wheels, you can choose more, you can enjoy at a variety of different speeds.

The wheel is the great invention of mankind.

Python is like this, there are all kinds of wheels, we just need to use. But those wheels in Python name is not called bicycles, cars, called "module", someone to undertake the name of another language, called "Class Library", "class". No matter what name you call it. is something that someone else made, and we take it.

How to use it? Can be used in two ways:

Form 1:import Module-name. Import followed by a space, followed by the module name, for example: import OS
Form 2:from Module1 import module11. Module1 is a large module, inside there are sub-modules Module11, just want to use MODULE11, so write.
Not verbose, experiment one:


>>> from the future import pision>>> 5/22.5>>> 9/24.5>>> 9.0/24.5>>> 9/2. 04.5


Note that once a module is referenced, the division is done, and whatever the case, it is the result of the floating-point number.

This is the power of the wheel.

Remainder
Before calculating 5/2, the quotient is 2, the remainder is 1.

How do we get the remainder? In Python (in fact most languages are also), use the% symbol to get the remainder of the two-digit divide.

Experiment with the following actions:


>>> 5 21>>> 6%42>>> 5.0%21.0


Symbol:%, which is the remainder to divide by two numbers (which can be integers or floating-point numbers).

The front says Python has a lot of people to love the wheel (module), she also has a wealth of built-in functions, will also help us do a lot of things. For example, function Pmod ()


>>> Pmod (5,2) # indicates 5 divided by 2, returns the quotient and remainder (2, 1) >>> Pmod (9,2) (4, 1) >>> Pmod (5.0,2) (2.0, 1.0)


Rounded
The last one, must insist, today is indeed a bit wordy. To achieve rounding, it is simple, that is, the built-in function: round ()

Try it yourself:


>>> round (1.234567,2) 1.23>>> round (1.234567,3) 1.235>>> round ( 10.0/3,4) 3.3333 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.