Table of Contents
Using the Decimal module
module can be of great help in this case.
Portform and denominator functions
Score and math module
Summary
Home Backend Development Python Tutorial Mathematical Modules in Python: Decimal and Fractions

Mathematical Modules in Python: Decimal and Fractions

Mar 09, 2025 am 09:15 AM

Mathematical Modules in Python: Decimal and Fractions

Even the most basic mathematical operations can sometimes produce wrong results. This is due to the limitations in storing the exact values ​​of certain numbers. You can overcome these limitations by using the decimal module in Python. Similarly, neither the math and cmath modules we learned in the previous tutorial will help us perform fraction-based arithmetic operations. However, the fractions module in Python happens to do just that.

This tutorial will introduce these two modules and the different functions they provide.

Using the Decimal module

from decimal import Decimal

Decimal(121)
# 返回 Decimal('121')

Decimal(0.05)
# 返回 Decimal('0.05000000000000000277555756')

Decimal('0.05')
# 返回 Decimal('0.05')

Decimal((0, (8, 3, 2, 4), -3))
# 返回 Decimal('8.324')

Decimal((1, (8, 3, 2, 4), -1))
# 返回 Decimal('-832.4')
Copy after login
Copy after login

As you can see, the value of the getcontext() function determines the accuracy of the calculation, rounding rules, and exception-raising behavior.

You can use the setcontext() function to get and set the current context of the calculation. Use the with statement to temporarily change the context of the calculation.

There are three built-in contexts in the

module that can be used for calculations: ROUND_HALF_UP, ROUND_HALF_EVEN and ROUND_HALF_EVEN as their rounding algorithms. Another difference between these contexts is the exception-provoking behavior. DefaultContextNo exceptions related to numerical overflow, invalid operation, and division by zero are raised. BasicContext enables almost all exceptions, which is great for debugging, while DefaultContext is used as the default context for calculations.

The following is an example of how to use different contexts to get different results for simple division:

import decimal
from decimal import ROUND_DOWN, ROUND_UP, Decimal as D

dec_a = D('0.153')
dec_b = D('0.231')
zero = D('0')

print("无上下文(使用默认值): ", dec_a/dec_b)
# 无上下文(使用默认值):  0.6623376623376623376623376623

decimal.setcontext(decimal.BasicContext)
print("基本上下文: ", dec_a/dec_b)
# 基本上下文:  0.662337662

decimal.setcontext(decimal.ExtendedContext)
print("扩展上下文: ", dec_a/dec_b)
# 扩展上下文:  0.662337662
print("扩展上下文: ", dec_b/zero)
# 扩展上下文:  Infinity

decimal.setcontext(decimal.DefaultContext)
print("默认上下文: ", dec_a/dec_b)
# 默认上下文:  0.6623376623376623376623376623

with decimal.localcontext() as l_ctx:
    l_ctx.prec = 5
    l_ctx.rounding = ROUND_UP

    print("局部上下文: ", dec_a/dec_b)
    # 局部上下文:  0.66234
Copy after login
Copy after login

In addition to noting the differences in precision and rounding algorithms for different contexts, you may also observe that under ExtendedContext, the division result for 0 is Infinity.

decimal Many functions in the

import decimal
from decimal import Decimal as D


print(D('22').sqrt(decimal.BasicContext))
# 4.69041576

print(D('22').sqrt(decimal.ExtendedContext))
# 4.69041576

print(D('22').sqrt(decimal.DefaultContext))
# 4.690415759823429554565630114

with decimal.localcontext() as l_ctx:
    l_ctx.prec = 5

    print(D('22').sqrt(l_ctx))
    # 4.6904
Copy after login
Copy after login
also accept context objects as parameters to perform their calculations. This way, you can avoid constantly setting the calculated context or precision values.

Using the Fractions modulefractions

Sometimes, you may encounter situations where you need to perform various operations on the score or the end result needs to be a score. The

module can be of great help in this case.

Create scorefractions The Fractiondecimal module allows you to create

instances from numbers, floating point numbers, decimal numbers and even strings. Like the
from fractions import Fraction
from decimal import Decimal

Fraction(11, 35)
# 返回 Fraction(11, 35)

Fraction(10, 18)
# 返回 Fraction(5, 9)

Fraction('8/25')
# 返回 Fraction(8, 25)

Fraction(1.13)
# 返回 Fraction(1272266894732165, 1125899906842624)

Fraction('1.13')
# 返回 Fraction(113, 100)

Fraction(Decimal('1.13'))
# 返回 Fraction(113, 100)
Copy after login
module, there are some problems with this module when creating fractions from floating point numbers. Here are some examples:

Arithmetic operation of fractions

You can also perform simple mathematical operations on fractions like normal numbers, such as addition and subtraction.
from decimal import Decimal

Decimal(121)
# 返回 Decimal('121')

Decimal(0.05)
# 返回 Decimal('0.05000000000000000277555756')

Decimal('0.05')
# 返回 Decimal('0.05')

Decimal((0, (8, 3, 2, 4), -3))
# 返回 Decimal('8.324')

Decimal((1, (8, 3, 2, 4), -1))
# 返回 Decimal('-832.4')
Copy after login
Copy after login

Portform and denominator functions

The module also has some important methods, such as limit_denominator(max_denominator), which will find and return a fraction closest to the value given fraction, with a denominator of at most max_denominator. You can also use the numerator attribute to return the numerator of a given fraction (denoted as the lowest term) and the denominator attribute to return the denominator.

import decimal
from decimal import ROUND_DOWN, ROUND_UP, Decimal as D

dec_a = D('0.153')
dec_b = D('0.231')
zero = D('0')

print("无上下文(使用默认值): ", dec_a/dec_b)
# 无上下文(使用默认值):  0.6623376623376623376623376623

decimal.setcontext(decimal.BasicContext)
print("基本上下文: ", dec_a/dec_b)
# 基本上下文:  0.662337662

decimal.setcontext(decimal.ExtendedContext)
print("扩展上下文: ", dec_a/dec_b)
# 扩展上下文:  0.662337662
print("扩展上下文: ", dec_b/zero)
# 扩展上下文:  Infinity

decimal.setcontext(decimal.DefaultContext)
print("默认上下文: ", dec_a/dec_b)
# 默认上下文:  0.6623376623376623376623376623

with decimal.localcontext() as l_ctx:
    l_ctx.prec = 5
    l_ctx.rounding = ROUND_UP

    print("局部上下文: ", dec_a/dec_b)
    # 局部上下文:  0.66234
Copy after login
Copy after login

Score and math module

You can also use this module with various functions in the math module to perform fraction-based calculations.

import decimal
from decimal import Decimal as D


print(D('22').sqrt(decimal.BasicContext))
# 4.69041576

print(D('22').sqrt(decimal.ExtendedContext))
# 4.69041576

print(D('22').sqrt(decimal.DefaultContext))
# 4.690415759823429554565630114

with decimal.localcontext() as l_ctx:
    l_ctx.prec = 5

    print(D('22').sqrt(l_ctx))
    # 4.6904
Copy after login
Copy after login

Summary

These two modules should be enough to help you perform common operations on decimal numbers and fractions. As shown in the last section, you can use these modules with the math module to calculate the values ​​of various mathematical functions in the format you wish.

In the next tutorial in this series, you will learn the random module in Python.

The above is the detailed content of Mathematical Modules in Python: Decimal and Fractions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles