数字图像处理 python_5使用Python处理数字的高级操作

数字图像处理 python

Numbers are everywhere in our daily life — there are phone numbers, dates of birth, ages, and other various identifiers (driver’s license and social security numbers, for example).

电话号码在我们的日常生活中无处不在-电话号码,生日,年龄和其他各种标识(例如,驾照和社会保险号)。

Naturally, all programming languages have a wide range of functionalities to process numbers. Most of these operations are based on common arithmetic operators — addition, subtraction, multiplication, and division — and everyone should be very familiar with them. However, various programming languages have unique operations that newcomers often find less intuitive.

自然,所有编程语言都具有处理数字的广泛功能。 这些操作大多数基于通用算术运算符(加,减,乘和除),每个人都应该非常熟悉它们。 但是,各种编程语言都具有独特的操作,新手常常不那么直观。

In this article, I’d like to review five advanced operations for handling numbers in Python.

在本文中,我想回顾一下在Python中处理数字的五种高级操作。

1.较少使用的运算符 (1. Less-Used Operators)

As we all know, addition, subtraction, multiplication, and division are the most basic mathematical operators. However, there are three other operators that we use less but are quite handy.

众所周知,加,减,乘和除是最基本的数学运算符。 但是,还有其他三个运算符,我们使用的较少,但非常方便。

  • The modulus operator, %, returns the remainder after the division of one number by the other number.

    模运算符%返回一个数除以另一个数后的余数。

  • The exponentiation operator ** returns the result after raising a number to the power of another number.

    取幂运算符**将一个数字乘以另一个数字的幂后返回结果。

  • The floor division operator // returns the largest possible result (e.g. rounding down 2.x to 2) after the division of one number by the other number.

    楼层除法运算符//返回一个数除以另一个数后的最大可能结果(例如,将2.x向下舍入为2)。

Please see some examples in the below code snippet. Notably, you don’t have to use integers for these operations, because they can also work on floats.

请在下面的代码片段中查看一些示例。 值得注意的是,这些操作不必使用整数,因为它们也可以在浮点数上使用。

Operators: %, **, and //
运算符:%,**和//

Among these operators, here are two specific use cases that you may find handy.

在这些运算符中,您可以使用以下两种特定的使用案例。

  • To find out whether an integer is even or odd, you can simply check its modulo by dividing it by 2 and comparing it with 0 or 1 (e.g., x % 2 == 1 will evaluate if it’s odd).

    要确定整数是偶数还是奇数,只需将其除以2并与0或1进行比较即可检查其模数(例如, x % 2 == 1将评估其为奇数)。

  • For the floor division operation, a use in data processing is to find out the number of data points down-sampled from time-series data, such as x // 4, which will down-sample the data to the quarter.

    对于楼层分割操作,数据处理中的一种用途是从时间序列数据(例如x // 4 )中找出向下采样的数据点的数量,这会将数据向下采样至四分之一。

2.赋值运算符 (2. Assignment Operators)

We all know that we use the equation operator, =, to assign values to variables — hence it’s also known as the assignment operator. As in many other programming languages, the arithmetic operators can be used together with the assignment operator to create a shortcut to manipulate the value of an existing variable. For instance, x += 5 is equivalent to x = x+5, and x *= 3 is equivalent to x = x*3. These operations should be straightforward. The following code snippet shows you some trivial examples:

我们都知道我们使用方程运算符=来给变量赋值-因此也称为赋值运算符。 与许多其他编程语言一样,算术运算符可以与赋值运算符一起使用,以创建快捷方式来操纵现有变量的值。 例如, x += 5等效于x = x+5 ,并且x *= 3等效于x = x*3 。 这些操作应该很简单。 以下代码段显示了一些简单的示例:

Assignment Operators
赋值运算符

The above example shows you some examples of assignment operations using some less-used operators, as discussed in the previous section. As a side note, some assignment operators can work with sequence data, which you may find helpful sometimes.

上面的示例显示了一些使用一些较少使用的运算符进行赋值操作的示例,如上一节所述。 附带说明,某些赋值运算符可以使用序列数据,有时您会发现这很有用。

Assignment Operator With Lists
带列表的赋值运算符

3.小数精度 (3. Precision With Decimal)

Suppose we’re solving a very simple addition question. We define two variables with one being 2.2 and the other being 1.1. What’s the sum of these two numbers? Relatedly, is the sum equal to 3.3? I’m sure that you’re very confident with your answers, but let’s use Python to help us solve this question:

假设我们正在解决一个非常简单的加法问题。 我们定义两个变量,一个为2.2,另一个为1.1。 这两个数字的总和是多少? 相关地,总和等于3.3吗? 我确定您对答案非常有信心,但是让我们使用Python帮助我们解决此问题:

Precision Problem
精度问题

Can you believe what you’ve just seen? No kidding — I didn’t make this up. Feel free to try it on your machine too.

你能相信你刚才看到的吗? 别开玩笑-我没有弥补。 也可以在您的计算机上尝试。

Actually, you shouldn’t be surprised about these results, if you understand that these floating-point numbers are not precisely stored in the memory. A complete discussion of these underlying mechanisms are beyond the scope of the present article, but if you’re interested, you can refer to a relevant discussion on StackOverflow.

实际上,如果您了解这些浮点数未精确存储在内存中,那么您就不会对这些结果感到惊讶。 这些基础机制的完整讨论不在本文的讨论范围之内,但是,如果您有兴趣,可以参考StackOverflow的相关讨论。

Fortunately, Python has a special module — decimal — to support these operations with desired precision. These precise operations can be particularly important in areas where precision is key, such as physics and the financial industry. Let’s see how it works with some trivial examples:

幸运的是,Python有一个特殊的模块- decimal —以所需的精度支持这些操作。 在诸如物理学和金融业等以精度为关键的领域中,这些精确的操作尤其重要。 让我们用一些简单的例子看看它是如何工作的:

Use of Decimal
小数的使用

As shown above, we created floating-point numbers using the Decimal class. Importantly, we use strings to instantiate Decimal objects. If we check the value of the c_Decimal, you’ll find that it’s the correct amount (i.e., 3.3). However, if you compare it with 3.3 directly, you’ll find that they’re not the same.

如上所示,我们使用Decimal类创建了浮点数。 重要的是,我们使用字符串来实例化Decimal对象。 如果我们检查c_Decimal的值,您会发现它是正确的数量(即3.3)。 但是,如果直接将其与3.3进行比较,您会发现它们并不相同。

Such inequality can be expected because a regular floating-point’s true value isn’t exactly the same as it appears. In addition, the regular floating-point number belongs to the float class, while the c_Decimal belongs to the Decimal class. Notably, we can compare it with another Decimal instance created using the same floating-point number.

可以预料到这样的不平等,因为常规浮点的真实值与其显示的值并不完全相同。 此外,常规浮点数属于float类,而c_Decimal属于Decimal类。 值得注意的是,我们可以将其与使用相同浮点数创建的另一个Decimal实例进行比较。

Relatedly, the above code shows you that we can use the addition operation with two Decimal instances. Actually, other common operations (such as subtraction and division) are also available to them.

相关地,上面的代码向您展示了我们可以对两个Decimal实例使用加法运算。 实际上,其他常用操作(例如减法和除法)也可以使用。

4.分数 (4. Fractions)

In most cases, we use floating-point numbers to denote the amount with sufficient precision. For instance, if you divide 1 by 9, you get 0.1111111111111111, which gives you 16-digit precision. Although this level of precision with the aid of the Decimal class serves our purposes in various scenarios, from a mathematical perspective, it’s not exactly right.

在大多数情况下,我们使用浮点数来足够精确地表示金额。 例如,如果将1除以9,则得到0.1111111111111111,这将为您提供16位精度。 尽管在Decimal类的帮助下达到这种精确度可以在各种情况下满足我们的目的,但从数学角度来看,这并不完全正确。

Fortunately, Python has a special package, Fraction, to deal with these fraction-related arithmetic operations. Overall, the usages are similar to the Decimal class. Let’s see them in action:

幸运的是,Python有一个特殊的包Fraction ,用于处理这些与分数相关的算术运算。 总体而言,用法类似于Decimal类。 让我们看看它们的作用:

Fractions
分数

As shown above, to create a fraction, you instantiate a Fraction object, specifying the numerator and the denominator. They support the arithmetic operations that we’ve covered previously, such as addition and multiplication. Besides these basic usages, the following code snippet shows you additional commonly needed operations:

如上所示,要创建一个分数,您可以实例化一个Fraction对象,并指定分子和分母。 它们支持我们前面介绍的算术运算,例如加法和乘法。 除了这些基本用法之外,以下代码段还向您显示了其他常用的操作:

Additional Operations on Fractions
分数的附加运算

There are a few things to highlight in the above code.

上面的代码中有几件事要强调。

  • Normalization is controlled by setting the _normalize parameter during the instantiation. By default, the fraction will be normalized to the smallest possible denominator.

    通过在实例化期间设置_normalize参数来控制规范化。 默认情况下,分数将被归一化为最小的分母。

  • To convert a floating-point number to a fraction, using the as_integer_ratio() function on the float will return a tuple. We use the asterisk to unpack the tuple, the elements of which (i.e., (1, 2) in our case) are used to create the new fraction.

    要将浮点数转换为分数,在浮点数上使用as_integer_ratio()函数将返回一个元组。 我们使用星号将元组解包,元组的元素(即本例中的(1, 2) )用于创建新的分数。

5.字符串的格式编号 (5. Format Numbers for Strings)

It’s common to need to display numbers as strings. In many cases, we want formatting such that the numbers are easier to read for the task at hand.

通常需要将数字显示为字符串。 在许多情况下,我们希望进行格式化,以便于手头的任务更易于阅读数字。

For instance, if we’re displaying a very large number involving multiple digits, you may want separators to better understand the number, as shown below:

例如,如果我们显示一个包含多个数字的非常大的数字,您可能希望分隔符更好地理解该数字,如下所示:

Large Numbers
大数

Suppose we want to display floating-point numbers with two-digit precision, such as the average score from a list of grades for a particular student. Consider the trivial example below.

假设我们要显示两位数精度的浮点数,例如特定学生的成绩列表中的平均分数。 考虑下面的简单示例。

A couple of things to note here:

这里需要注意几件事:

  1. The last example used the format() method, while the below example uses the f-strings, which just shows you there are multiple ways to format strings.

    最后一个示例使用format()方法,而下面的示例使用f-strings ,它仅向您显示了格式化字符串的多种方法。

  2. The other way to format the floating-point number is to use the round() method, which creates a new floating-point number with the desired precision. Please note that using round() is different from the string formatting, which doesn’t create a new floating-point number.

    格式化浮点数的另一种方法是使用round()方法,该方法创建具有所需精度的新浮点数。 请注意,使用round()与字符串格式不同,后者不会创建新的浮点数。

Floating-Point Precision
浮点精度

In a scientific computation project, numbers can get very large or very small, in which cases, scientific notations are relevant techniques — as shown below:

在科学计算项目中,数字可能会变得很大或非常小,在这种情况下,科学计数法是相关的技术,如下所示:

Scientific Notation
科学计数法

It’s also very common to display the numbers in the percent, such as the interest rate and other small amounts like the discount rate for a promotional sale event. Some trivial examples are shown. Notably, we can control the precision by specifying the value before the percent sign.

以百分比显示数字也是很常见的,例如利率和其他少量金额,例如促销活动的折扣率。 显示了一些简单的示例。 值得注意的是,我们可以通过在百分号前指定值来控制精度。

Percentage
百分比

结论 (Conclusions)

In this article, we reviewed five advanced techniques to handle numbers in Python. Here’s a quick recap.

在本文中,我们回顾了使用Python处理数字的五种先进技术。 快速回顾一下。

  • In addition to the basic operators (+, -, *, /), we can use the % to calculate modulo, ** to calculate exponentiation, and // to calculate floor divisions.

    除了基本运算符(+,-,*,/)外,我们还可以使用%来计算模数,使用**来计算指数,并//来计算底数除法。
  • These arithmetic operators can be used with the assignment operators, which assignment the value after performing the applicable operations.

    这些算术运算符可与赋值运算符一起使用,赋值运算符在执行适用的运算后赋值。
  • If we need precise calculations, we need to use the Decimal class which is part of the decimal module in the standard library.

    如果需要精确的计算,则需要使用Decimal类,它是标准库中小数模块的一部分。

  • The Fraction class in the fractions module is particularly designed to deal with fractions.

    分数模块中的Fraction类专门设计用于处理分数。

  • The format() method of strings and the f-strings are handy tools to format numbers in the desired fashion, such as percentage and scientific notation.

    字符串和f字符串的format()方法是方便的工具,用于以所需的方式(例如百分比和科学计数法)格式化数字。

翻译自: https://medium.com/better-programming/5-advanced-operations-to-handle-numbers-in-python-e7ff921da475

数字图像处理 python

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值