Python Division and Remainders

本文详细解释了Python中除法和取余运算的规则与应用,包括整除、浮点除、整数结果和余数的计算方法。通过实际例子,帮助读者掌握不同情况下的运算行为。

Use a double percent sign (%%) if the command is used inside a batch file.

Division Operators

In general, the data type of an expresion depends on the types of the arguments. This rule meets our expectations for most operators: when we add two integers, the result should be an integer. However, this doesn't work out well for division because there are two different expectations. Sometimes we expect division to create precise answers, usually the floating-point equivalents of fractions. Other times, we want a rounded-down integer result.

The classical Python definition of / depended entirely on the arguments. 685/252 was 2 because both arguments where integers. However, 685./252. was 2.7182539682539684 because the arguments were floating point.

This definition often caused problems for applications where data types were used that the author hadn't expected. For example, a simple program doing Celsius to Fahrenheit conversions will produce different answers depending on the input. If one user provides 18 and another provides 18.0, the answers were different, even though all of the inputs all had the equal numeric values.

>>> 

print 18*9/5+32

64
>>> 

print 18.0*9/5 + 32

64.4
>>> 

18 == 18.0

True
>>> 

This unexpected inaccuracy was generally due to the casual use of integers where floating-point numbers were more appropriate. (This can also occur using integers where complex numbers were implictly expected.) An explicit conversion function (like float( x )) can help prevent this. The idea, however, is for Python be a simple and sparse language, without a dense clutter of conversions to cover the rare case of an unexpected data type.

Starting with Python 2.2, a new division operator was added to clarify what was expectred. The ordinary / operator will, in the future, return floating-point results. A special division operator, //, will return rounded-down results. Generally, the new /operator is what most mathematical processing will use.

In additional two tools were made avialable that will end with Python 3.0. These tools will allow the division operator, /, to operate either under the old (classical, prior to version 2.2) rules or the new rules. This gives programmers a way to keep older applications running; it also gives them a way to explicitly declare that a program uses the newer operator definition. There are two parts to this: a statememt that can be placed in a program, as well as a command-line option that can be used when starting the Python interpreter.

Program Statements. To ease the transition from older to newer language features, there is a __future__ module available. This module includes a division definition that changes the definition of the / operator from classical to future. You can include the following from statement to state that your program depends on the future definition of division.

from __future__ import division
print 18*9/5+32
print 18*9//5+32

This produces the following output. The first line shows the new use of the / operator to produce floating point results, even if both arguments are integers. The second line shows the // operator, which produces rounded-down results.

64.4
64

The from __future__ statement will set the expectation that your script uses the new-style floating-point division operator. This allows you to start writing programs with version 2.2 that will work correctly with all future versions. By version 3.0, this import statement will no longer be necessary, and these will have to be removed from the few modules that used them.

Programmers should put the from __future__ statement in every Python script file, to be sure that what they are writing will work correctly. Eventually, these can be removed, but for the forseeable future, they are a necessary part of each Python script file.

Command Line Options. Another tool to ease the transition is a command-line option used when running the Python interpreter. This can force old-style interpretation of the / operator or to warn about old-style use of the / operator between integers. It can also force new-style use of the / operator and report on all potentially incorrect uses of the / operator.

The Python interpreter command-line option of -Q will force the / operator to be treated classically (“old”), or with the future (“new”) semantics. If you run Python with -Qold, the / operator's result depends on the arguments. If you run Python with -Qnew, the / operator's result will be floating point. In either case, the // operator returns a rounded-down integer result.

You can use -Qold to force old modules and programs to work with version 2.2 and higher. When Python 3.0 is released, however, this transition will no longer be supported; by that time you should have fixed your programs and modules.

To make fixing easier, the -Q command-line option can take two other values: warn and warnall. If you use -Qwarn, then the /operator applied to integer arguments will generate a run-time warning. This will allow you to find and fix situations where the // operator might be more appropriate. If you use -Qwarnall, then all instances of the / operator generate a warning; this will give you a close look at your programs.

You can include the command line option when you run the Python interpreter. For Linux and MacOS users, you can also put this on the #! line at the beginning of your script file.

#!/usr/local/bin/python -Qnew

1.4.1. Addition and Subtraction

We start with the integers and integer arithmetic, not because arithmetic is exciting, but because the symbolism should be mostly familiar. Of course arithmetic is important in many cases, but Python is probably more often used to manipulate text and other sorts of data, as in the sample program in ref:Running-A-Sample.

Python understands numbers and standard arithmetic. For the whole section on integer arithmetic, where you see a set-off line in typewriter font, type individual lines at the >>> prompt in the Python Shell. Press Enter after each line to get Python to respond:

77
2 + 3
5 - 7

Python should evaluate and print back the value of each expression. Of course the first one does not require any calculation. It appears that the shell just echoes back what you printed.

The Python Shell is an interactive interpreter. As you can see, after you press Enter, it is evaluating the expression you typed in, and then printing the result automatically. This is a very handy environment to check out simple Python syntax and get instant feedback. For more elaborate programs that you want to save, we will switch to an Editor Window later.

1.4.2. Multiplication, Parentheses, and Precedence

Try in the Shell:

2 x 3

You should get your first syntax error. The x should have become highlighted, indicating the location where the Python interpreter discovered that it cannot understand you: Python does not use x for multiplication as you may have done in grade school. The x can be confused with the use of x as a variable (more on that later).

Instead the symbol for multiplication is an asterisk *. Enter each of the following. You may include spaces or not. The Python interpreter can figure out what you mean either way. Try in the Shell:

2*5
2 + 3 * 4

If you expected the last answer to be 20, think again: Python uses the normal precedence of arithmetic operations: Multiplications and divisions are done before addition and subtraction, unless there are parentheses. Try

(2+3)*4
2 * (4 - 1)

Now try the following in the Shell, exactly as written, followed by Enter, with no closing parenthesis:

5 * (2 + 3

Look carefully. There is no answer given at the left margin of the next line and no prompt >>> to start a new expression. If you are using Idle, the cursor has gone to the next line and has only indented slightly. Python is waiting for you to finish your expression. It is smart enough to know that opening parentheses are always followed by the same number of closing parentheses. The cursor is on a continuation line. Type just the matching close-parenthesis and Enter,

)

and you should finally see the expression evaluated. (In some versions of the Python interpreter, the interpreter puts ‘...’ at the beginning of a continuation line, rather than just indenting.)

Negation also works. Try in the Shell:

-(2 + 3)

1.4.3. Division and Remainders

If you think about it, you learned several ways to do division. Eventually you learned how to do division resulting in a decimal. Try in the Shell:

5/2
14/4

As you saw in the previous section, numbers with decimal points in them are of type float in Python. They are discussed more in Floats, Division, Mixed Types.

In the earliest grades you would say “14 divided by 4 is 3 with a remainder of 2”. The problem here is that the answer is in two parts, the integer quotient 3 and the remainder 2, and neither of these results is the same as the decimal result. Python has separate operations to generate each part. Python uses the doubled division symbol // for the operation that produces just the integer quotient, and introduces the symbol % for the operation of finding the remainder. Try each in the Shell:

14/4
14//4
14%4

Now predict and then try each of

23//5
23%5
20%5
6//8
6%8
6/8

Finding remainders will prove more useful than you might think in the future!



decimal

  常用词汇  
英 ['desɪml]     美 ['desɪml]   
  • adj.小数的;十进位的
  • n.小数



Noun:

  1. a proper fraction whose denominator is a power of 10

  2. a number in the decimal system

Adjective:
  1. numbered or proceeding by tens; based on ten;

    "the decimal system"

用作形容词 (adj.)
  1. The first two figures after the decimal point indicate tenths and hundredths respectively.
    小数点后的头两位数分别表示十分位和百分位。
  2. Most countries have a decimal currency.
    大多数国家使用十进制货币。
  3. There were only decimal math problem on the quiz.
    测验中只有十进位的数学题。
  4. Britain converted to a decimal currency system in 1971.
    英国于1971年改行十进制货币体系。
收起
用作名词 (n.)
  1. 0.3 is a decimal.
    0.
  2. What kind of decimal is called a repeating decimal ?
    谁能说说什么样的小数叫循环小数?

quotient

  扩展词汇  
Intelligence Quotient
英 ['kwəʊʃnt]     美 ['kwoʊʃnt]   
  • n.份额;[数]商
  • Noun:
    1. the ratio of two quantities to be divided

    2. the number obtained by division
    用作名词 (n.)
    1. He got a small quotient of his father's property.
      他得到了他父亲财产的一小部分。
    2. The result is the quotient of the two operands.
      结果是两个操作数的商。
    3. His intelligence quotient is very high.
      他的智商很高。



【顶级EI复现】计及连锁故障传播路径的电力系统 N-k 多阶段双层优化及故障场景筛选模型(Matlab代码实现)内容概要:本文介绍了名为《【顶级EI复现】计及连锁故障传播路径的电力系统 N-k 多阶段双层优化及故障场景筛选模型(Matlab代码实现)》的研究资源,重点围绕电力系统中连锁故障的传播机制,提出了一种N-k多阶段双层优化模型,并结合故障场景筛选方法提升系统安全性与鲁棒性。该模型通过Matlab代码实现,可用于模拟复杂电力系统在多重故障下的响应特性,支持对关键故障路径的识别与优化决策,适用于高水平科研复现与工程仿真分析。文中还列举了大量相关技术方向的配套资源,涵盖智能优化算法、电力系统管理、机器学习、路径规划等多个领域,并提供了网盘链接以便获取完整代码与资料。; 适合人群:具备电力系统、优化理论及Matlab编程基础的研究生、科研人员及从事能源系统安全分析的工程技术人员,尤其适合致力于高水平论文(如EI/SCI)复现与创新的研究者。; 使用场景及目标:①复现顶级期刊关于N-k故障与连锁传播的优化模型;②开展电力系统韧性评估、故障传播分析与多阶段防御策略设计;③结合YALMIP等工具进行双层优化建模与场景筛选算法开发;④支撑科研项目、学位论文或学术成果转化。; 阅读建议:建议读者按照文档提供的目录顺序系统学习,优先掌握双层优化与场景筛选的核心思想,结合网盘中的Matlab代码进行调试与实验,同时参考文中提及的智能算法与电力系统建模范例,深化对复杂电力系统建模与优化的理解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值