數字圖像處理 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.
請在下面的代碼片段中查看一些示例。 值得注意的是,這些操作不必使用整數,因為它們也可以在浮點數上使用。
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
。 這些操作應該很簡單。 以下代碼段顯示了一些簡單的示例:
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.
上面的示例顯示了一些使用一些較少使用的運算符進行賦值操作的示例,如上一節所述。 附帶說明,某些賦值運算符可以使用序列數據,有時您會發現這很有用。
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幫助我們解決此問題:
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
—以所需的精度支持這些操作。 在諸如物理學和金融業等以精度為關鍵的領域中,這些精確的操作尤其重要。 讓我們用一些簡單的例子看看它是如何工作的:
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
類。 讓我們看看它們的作用:
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
對象,并指定分子和分母。 它們支持我們前面介紹的算術運算,例如加法和乘法。 除了這些基本用法之外,以下代碼段還向您顯示了其他常用的操作:
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:
例如,如果我們顯示一個包含多個數字的非常大的數字,您可能希望分隔符更好地理解該數字,如下所示:
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:
這里需要注意幾件事:
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 ,它僅向您顯示了格式化字符串的多種方法。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 usinground()
is different from the string formatting, which doesn’t create a new floating-point number.格式化浮點數的另一種方法是使用
round()
方法,該方法創建具有所需精度的新浮點數。 請注意,使用round()
與字符串格式不同,后者不會創建新的浮點數。
In a scientific computation project, numbers can get very large or very small, in which cases, scientific notations are relevant techniques — as shown below:
在科學計算項目中,數字可能會變得很大或非常小,在這種情況下,科學計數法是相關的技術,如下所示:
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.
以百分比顯示數字也是很常見的,例如利率和其他少量金額,例如促銷活動的折扣率。 顯示了一些簡單的示例。 值得注意的是,我們可以通過在百分號前指定值來控制精度。
結論 (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
本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。 如若轉載,請注明出處:http://www.pswp.cn/news/388011.shtml 繁體地址,請注明出處:http://hk.pswp.cn/news/388011.shtml 英文地址,請注明出處:http://en.pswp.cn/news/388011.shtml
如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!