數字圖像處理 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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處: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,一經查實,立即刪除!

相關文章

05精益敏捷項目管理——超越Scrum

00.我們不是不知道它會給我們帶來麻煩,只是沒想到麻煩會有這么多。——威爾.羅杰斯 01.知識點: a.Scrum是一個強大、特意設計的輕量級框架,器特性就是將軟件開發中在制品的數量限制在團隊層級,使團隊有能力與業務落班一起有效地開…

帶標題的圖片輪詢展示

為什么80%的碼農都做不了架構師&#xff1f;>>> <div> <table width"671" cellpadding"0" cellspacing"0"> <tr height"5"> <td style"back…

linux java 查找進程中的線程

這里對linux下、sun(oracle) JDK的線程資源占用問題的查找步驟做一個小結&#xff1b;linux環境下&#xff0c;當發現java進程占用CPU資源很高&#xff0c;且又要想更進一步查出哪一個java線程占用了CPU資源時&#xff0c;按照以下步驟進行查找&#xff1a;(一)&#xff1a;通過…

定位匹配 模板匹配 地圖_什么是地圖匹配?

定位匹配 模板匹配 地圖By Marie Douriez, James Murphy, Kerrick Staley瑪麗杜里茲(Marie Douriez)&#xff0c;詹姆斯墨菲(James Murphy)&#xff0c;凱里克史塔利(Kerrick Staley) When you request a ride, Lyft tries to match you with the driver most suited for your…

Sprint計劃列表

轉載于:https://www.cnblogs.com/zhs20160715/p/9953586.html

MySQL學習【第十二篇事務中的鎖與隔離級別】

一.事務中的鎖 1.啥是鎖&#xff1f; 顧名思義&#xff0c;鎖就是鎖定的意思 2.鎖的作用是什么&#xff1f; 在事務ACID的過程中&#xff0c;‘鎖’和‘隔離級別’一起來實現‘I’隔離性的作用 3.鎖的種類 共享鎖&#xff1a;保證在多事務工作期間&#xff0c;數據查詢不會被阻…

Android WebKit

這段時間基于項目需要 在開發中與WebView的接觸比較多&#xff0c;前段時間關于HTML5規范塵埃落定的消息出現在各大IT社區頭版上&#xff0c;更有人說&#xff1a;HTML5將顛覆原生App開發 雖然我不太認同這一點 但是關于HTML5JSCSSNative的跨平臺開發模式還是為很多企業節省了開…

jQuery的事件綁定和解綁

1、綁定事件 語法&#xff1a; bind(type,data,fn) 描述&#xff1a;為每一個匹配元素的特定事件&#xff08;像click&#xff09;綁定一個事件處理器函數。 參數解釋&#xff1a; type (String) : 事件類型 data (Object) : (可選) 作為event.data屬性值傳遞給事件對象的額外數…

軟件測試框架課程考試_那考試準備課程值得嗎?

軟件測試框架課程考試By Levi Petty李維佩蒂(Levi Petty) This project uses a public, synthesized exam scores dataset from Kaggle to analyze average scores in Math, Reading, and Writing subject areas, relative to the student’s parents’ level of education an…

開博第一天

開博第一天 紀念一下 轉載于:https://www.cnblogs.com/yang-9654/p/9959388.html

GitLab 11.9 正式發布,自動化工具 ChatOps 已開源

GitLab 11.9 已正式發布&#xff0c;該版本新增了兩個和安全相關的特性&#xff0c;一是快速檢查私密信息是否泄漏&#xff0c;從該版本起在 CI/CD 過程中會掃描開發者提交的信息是否包含私密內容&#xff0c;有的話會在合并 PR 時向開發者發送警報&#xff1b;二是改進了合并 …

DOCKER windows安裝

DOCKER windows安裝 DOCKER windows安裝 1.下載程序包2. 設置環境變量3. 啟動DOCKERT4. 分析start.sh5. 利用SSH工具管理6. 下載鏡像 6.1 下載地址6.2 用FTP工具上傳tar包6.3 安裝6.4 查看鏡像6.5 運行 windows必須是64位的 1.下載程序包 安裝包 https://github.com/boot2doc…

為什么在Python代碼中需要裝飾器

Python is praised for its clarity and syntactic sugariness. In this article, I will teach you to use decorators in Python to make your code readable and clean.Python的清晰性和語法含糖度受到贊譽。 在本文中&#xff0c;我將教您在Python中使用裝飾器&#xff0c;…

Elasticsearch Reference [6.7] ? Modules ? Network Settings

2019獨角獸企業重金招聘Python工程師標準>>> Search Settings Node Network Settingsedit Elasticsearch binds to localhost only by default. This is sufficient for you to run a local development server (or even a development cluster, if you star…

【百度】大型網站的HTTPS實踐(一)——HTTPS協議和原理

大型網站的HTTPS實踐&#xff08;一&#xff09;——HTTPS協議和原理 原創 網絡通信/物聯網 作者&#xff1a;AIOps智能運維 時間&#xff1a;2018-11-09 15:07:39 349 0前言 百度于2015年上線了全站HTTPS的安全搜索&#xff0c;默認會將HTTP請求跳轉成HTTPS。從今天開始&…

數據清理最終實現了自動化

蘋果 | GOOGLE | 現貨 | 其他 (APPLE | GOOGLE | SPOTIFY | OTHERS) Editor’s note: The Towards Data Science podcast’s “Climbing the Data Science Ladder” series is hosted by Jeremie Harris. Jeremie helps run a data science mentorship startup called Sharpest…

mui 與jquery 同時使用,$沖突解決辦法。

(function($,doc,$$) { 。。。。。 }(mui, document, jQuery)); 使用$$代替jQuery。 var $$jQuery.noConflict();此方法也可以 轉載于:https://www.cnblogs.com/mustanglqt/p/10608499.html

LVS原理介紹及安裝過程

一、ARP技術概念介紹 為什么講ARP技術&#xff0c;因為平常工作中有接觸。還有就是LVS的dr模式是用到arp的技術和數據。 1、什么是ARP協議 ARP協議全程地址解析協議&#xff08;AddressResolution Protocol&#xff0c;ARP&#xff09;是在僅知道主機的IP地址時確定其物理地…

Python氣流介紹

This is a memo to share what I have learnt in Apache Airflow, capturing the learning objectives as well as my personal notes. The course is taught by Mike Metzger from DataCamp.這是一份備忘錄&#xff0c;旨在分享我在Apache Airflow中學到的知識&#xff0c;記錄…

java~springcloud微服務目錄索引

回到占占推薦博客索引 最近寫了不過關于java&#xff0c;spring&#xff0c;微服務的相關文章&#xff0c;今天把它整理一下&#xff0c;方便大家學習與參考。 java~springcloud微服務~目錄索引 springcloud~服務注冊與發現Eureka的使用 springcloud~配置中心的使用 springclou…