How does python represent scores

How does python represent scores

The Fraction function is a module that implements scores in python. It can be used directly as a code program, including definitions of classes, functions, and labels, and is part of the python standard library.
To use it, you must first insert the module.

from fractions import Fraction #insert
module

f =Fraction(1,2)
#Create Fraction class and initialize it to 1/2

print(f)
#output fractional object Fraction(1, 2)

When entering the score, the initial letter of Fraction must be capitalized, otherwise an error will be reported.
If the float data type appears in the Fraction(2,8)+1+1.52.75 operation, the final result will be float type data. If there are only integer type and fraction type in the expression, the output result will be the fraction type. >>> >>> Fraction(2,8)+Fraction(2,5)+3 #Output
: Fraction(73, 20)
Fraction() method, very interesting, you can directly receive the fraction string into input. Note that the entered score must be quoted.

a = Fraction('1/5')
print(a)
#Output: Fraction(1, 5)

Enter the decimal directly, and the Fraction method directly turns the decimal into a fraction.

from decimal import Decimal
Fraction(1.1)
#输出:Fraction(11, 10)

To turn a string into a decimal, you need to use the decimal class, and then turn the decimal into a fraction.

from decimal import Decimal
Fraction(Decimal('1.1'))
#Output: Fraction(11, 10)
first turns 1.1 string into a decimal, and then into a fraction.

Related recommendation: "Python Video Tutorial"
Feature 1: Automatic
reduction When there is a negative sign in the numerator and denominator, automatically reduce the division and finally assign the negative sign to the numerator

Fraction(10, -5)
Fraction(-2, 1)

Feature 2: Binary operations:
add two fractions to get a score,
add a score to an integer to get a
score, add a score to a floating point number to get a floating point number, and
other binary operations are the same as addition.
Feature 3: Get the
literal meaning of the Fraction object property , numerator Get the numerator, denominator get the denominator
Feature 4: gcd quickly get the greatest common divisor

from fractions import gcd
gcd(9, 6)
#输出:3

Example: s=1+1/2+1/3+1/4+…+1/9

s =1
for i in range(1,10):
s=s+Fraction(1,i)

print(s)
#Output: 9649/2520

Study notes come
from:Insert picture description here

Guess you like

Origin blog.csdn.net/m0_53052839/article/details/110307498