0.1 + 0.1 + 0.1
0.30000000000000004
round(1.111 + 1.111 + 1.111, 3)
3.333
round(1.111 + 1.111 + 1.111, 2)
3.33
round(1.111 + 1.111 + 1.111, 1)
3.3
round(1.111 + 1.111 + 1.111, 0)
3.0
round(1.111 + 1.111 + 1.111)
3
round(1.0 + 1.0 + 1.0, 2)
3.0
0.6 + 0.3 + 0.1 # 반드시 1.0이 되어야 한다.
0.9999999999999999
(0.6 + 0.3 + 0.1) / 2 # 반드시 0.5이 되어야 한다.
0.49999999999999994
from decimal import Decimal
my_dec = Decimal()
print(my_dec)
0
d = Decimal('0.1')
print(d + d + d)
0.3
d = Decimal(0.1)
print(d)
0.1000000000000000055511151231257827021181583404541015625
d = Decimal('0.1')
print(d + d + d)
0.3
print(0.1 + 0.1 + 0.1)
0.30000000000000004
print(0.1 + 0.1 + 0.1 - 0.3)
d1, d3 = Decimal('0.1'), Decimal('0.3')
print(d1 + d1 + d1 - d3)
5.551115123125783e-17 0.0
d1, d3 = Decimal('0.10'), Decimal('0.30')
d1 + d3
Decimal('0.40')
d1, d2 = Decimal('0.50'), Decimal('0.50')
print(d1 + d2)
1.00
d1, d3 = Decimal('0.020'), Decimal('0.030')
print(d1 * d3)
0.000600
print(round(d1 * d3, 4))
print(round(d1 * d3, 3))
0.0006 0.001
d = Decimal(5)
d
Decimal('5')
d = Decimal(533)
d += 2
print(round(d, 2))
535.00
help(Decimal)
Help on class Decimal in module decimal: class Decimal(builtins.object) | Decimal(value='0', context=None) | | Construct a new Decimal object. 'value' can be an integer, string, tuple, | or another Decimal object. If no value is given, return Decimal('0'). The | context does not affect the conversion and is only passed to determine if | the InvalidOperation trap is active. | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __bool__(self, /) | self != 0 | | __ceil__(...) | | __complex__(...) | | __copy__(...) | | __deepcopy__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floor__(...) | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | Default object formatter. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __int__(self, /) | int(self) | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __round__(...) | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __sizeof__(...) | Size of object in memory, in bytes. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __trunc__(...) | | adjusted(self, /) | Return the adjusted exponent of the number. Defined as exp + digits - 1. | | as_integer_ratio(self, /) | Decimal.as_integer_ratio() -> (int, int) | | Return a pair of integers, whose ratio is exactly equal to the original | Decimal and with a positive denominator. The ratio is in lowest terms. | Raise OverflowError on infinities and a ValueError on NaNs. | | as_tuple(self, /) | Return a tuple representation of the number. | | canonical(self, /) | Return the canonical encoding of the argument. Currently, the encoding | of a Decimal instance is always canonical, so this operation returns its | argument unchanged. | | compare(self, /, other, context=None) | Compare self to other. Return a decimal value: | | a or b is a NaN ==> Decimal('NaN') | a < b ==> Decimal('-1') | a == b ==> Decimal('0') | a > b ==> Decimal('1') | | compare_signal(self, /, other, context=None) | Identical to compare, except that all NaNs signal. | | compare_total(self, /, other, context=None) | Compare two operands using their abstract representation rather than | their numerical value. Similar to the compare() method, but the result | gives a total ordering on Decimal instances. Two Decimal instances with | the same numeric value but different representations compare unequal | in this ordering: | | >>> Decimal('12.0').compare_total(Decimal('12')) | Decimal('-1') | | Quiet and signaling NaNs are also included in the total ordering. The result | of this function is Decimal('0') if both operands have the same representation, | Decimal('-1') if the first operand is lower in the total order than the second, | and Decimal('1') if the first operand is higher in the total order than the | second operand. See the specification for details of the total order. | | This operation is unaffected by context and is quiet: no flags are changed | and no rounding is performed. As an exception, the C version may raise | InvalidOperation if the second operand cannot be converted exactly. | | compare_total_mag(self, /, other, context=None) | Compare two operands using their abstract representation rather than their | value as in compare_total(), but ignoring the sign of each operand. | | x.compare_total_mag(y) is equivalent to x.copy_abs().compare_total(y.copy_abs()). | | This operation is unaffected by context and is quiet: no flags are changed | and no rounding is performed. As an exception, the C version may raise | InvalidOperation if the second operand cannot be converted exactly. | | conjugate(self, /) | Return self. | | copy_abs(self, /) | Return the absolute value of the argument. This operation is unaffected by | context and is quiet: no flags are changed and no rounding is performed. | | copy_negate(self, /) | Return the negation of the argument. This operation is unaffected by context | and is quiet: no flags are changed and no rounding is performed. | | copy_sign(self, /, other, context=None) | Return a copy of the first operand with the sign set to be the same as the | sign of the second operand. For example: | | >>> Decimal('2.3').copy_sign(Decimal('-1.5')) | Decimal('-2.3') | | This operation is unaffected by context and is quiet: no flags are changed | and no rounding is performed. As an exception, the C version may raise | InvalidOperation if the second operand cannot be converted exactly. | | exp(self, /, context=None) | Return the value of the (natural) exponential function e**x at the given | number. The function always uses the ROUND_HALF_EVEN mode and the result | is correctly rounded. | | fma(self, /, other, third, context=None) | Fused multiply-add. Return self*other+third with no rounding of the | intermediate product self*other. | | >>> Decimal(2).fma(3, 5) | Decimal('11') | | is_canonical(self, /) | Return True if the argument is canonical and False otherwise. Currently, | a Decimal instance is always canonical, so this operation always returns | True. | | is_finite(self, /) | Return True if the argument is a finite number, and False if the argument | is infinite or a NaN. | | is_infinite(self, /) | Return True if the argument is either positive or negative infinity and | False otherwise. | | is_nan(self, /) | Return True if the argument is a (quiet or signaling) NaN and False | otherwise. | | is_normal(self, /, context=None) | Return True if the argument is a normal finite non-zero number with an | adjusted exponent greater than or equal to Emin. Return False if the | argument is zero, subnormal, infinite or a NaN. | | is_qnan(self, /) | Return True if the argument is a quiet NaN, and False otherwise. | | is_signed(self, /) | Return True if the argument has a negative sign and False otherwise. | Note that both zeros and NaNs can carry signs. | | is_snan(self, /) | Return True if the argument is a signaling NaN and False otherwise. | | is_subnormal(self, /, context=None) | Return True if the argument is subnormal, and False otherwise. A number is | subnormal if it is non-zero, finite, and has an adjusted exponent less | than Emin. | | is_zero(self, /) | Return True if the argument is a (positive or negative) zero and False | otherwise. | | ln(self, /, context=None) | Return the natural (base e) logarithm of the operand. The function always | uses the ROUND_HALF_EVEN mode and the result is correctly rounded. | | log10(self, /, context=None) | Return the base ten logarithm of the operand. The function always uses the | ROUND_HALF_EVEN mode and the result is correctly rounded. | | logb(self, /, context=None) | For a non-zero number, return the adjusted exponent of the operand as a | Decimal instance. If the operand is a zero, then Decimal('-Infinity') is | returned and the DivisionByZero condition is raised. If the operand is | an infinity then Decimal('Infinity') is returned. | | logical_and(self, /, other, context=None) | Return the digit-wise 'and' of the two (logical) operands. | | logical_invert(self, /, context=None) | Return the digit-wise inversion of the (logical) operand. | | logical_or(self, /, other, context=None) | Return the digit-wise 'or' of the two (logical) operands. | | logical_xor(self, /, other, context=None) | Return the digit-wise 'exclusive or' of the two (logical) operands. | | max(self, /, other, context=None) | Maximum of self and other. If one operand is a quiet NaN and the other is | numeric, the numeric operand is returned. | | max_mag(self, /, other, context=None) | Similar to the max() method, but the comparison is done using the absolute | values of the operands. | | min(self, /, other, context=None) | Minimum of self and other. If one operand is a quiet NaN and the other is | numeric, the numeric operand is returned. | | min_mag(self, /, other, context=None) | Similar to the min() method, but the comparison is done using the absolute | values of the operands. | | next_minus(self, /, context=None) | Return the largest number representable in the given context (or in the | current default context if no context is given) that is smaller than the | given operand. | | next_plus(self, /, context=None) | Return the smallest number representable in the given context (or in the | current default context if no context is given) that is larger than the | given operand. | | next_toward(self, /, other, context=None) | If the two operands are unequal, return the number closest to the first | operand in the direction of the second operand. If both operands are | numerically equal, return a copy of the first operand with the sign set | to be the same as the sign of the second operand. | | normalize(self, /, context=None) | Normalize the number by stripping the rightmost trailing zeros and | converting any result equal to Decimal('0') to Decimal('0e0'). Used | for producing canonical values for members of an equivalence class. | For example, Decimal('32.100') and Decimal('0.321000e+2') both normalize | to the equivalent value Decimal('32.1'). | | number_class(self, /, context=None) | Return a string describing the class of the operand. The returned value | is one of the following ten strings: | | * '-Infinity', indicating that the operand is negative infinity. | * '-Normal', indicating that the operand is a negative normal number. | * '-Subnormal', indicating that the operand is negative and subnormal. | * '-Zero', indicating that the operand is a negative zero. | * '+Zero', indicating that the operand is a positive zero. | * '+Subnormal', indicating that the operand is positive and subnormal. | * '+Normal', indicating that the operand is a positive normal number. | * '+Infinity', indicating that the operand is positive infinity. | * 'NaN', indicating that the operand is a quiet NaN (Not a Number). | * 'sNaN', indicating that the operand is a signaling NaN. | | quantize(self, /, exp, rounding=None, context=None) | Return a value equal to the first operand after rounding and having the | exponent of the second operand. | | >>> Decimal('1.41421356').quantize(Decimal('1.000')) | Decimal('1.414') | | Unlike other operations, if the length of the coefficient after the quantize | operation would be greater than precision, then an InvalidOperation is signaled. | This guarantees that, unless there is an error condition, the quantized exponent | is always equal to that of the right-hand operand. | | Also unlike other operations, quantize never signals Underflow, even if the | result is subnormal and inexact. | | If the exponent of the second operand is larger than that of the first, then | rounding may be necessary. In this case, the rounding mode is determined by the | rounding argument if given, else by the given context argument; if neither | argument is given, the rounding mode of the current thread's context is used. | | radix(self, /) | Return Decimal(10), the radix (base) in which the Decimal class does | all its arithmetic. Included for compatibility with the specification. | | remainder_near(self, /, other, context=None) | Return the remainder from dividing self by other. This differs from | self % other in that the sign of the remainder is chosen so as to minimize | its absolute value. More precisely, the return value is self - n * other | where n is the integer nearest to the exact value of self / other, and | if two integers are equally near then the even one is chosen. | | If the result is zero then its sign will be the sign of self. | | rotate(self, /, other, context=None) | Return the result of rotating the digits of the first operand by an amount | specified by the second operand. The second operand must be an integer in | the range -precision through precision. The absolute value of the second | operand gives the number of places to rotate. If the second operand is | positive then rotation is to the left; otherwise rotation is to the right. | The coefficient of the first operand is padded on the left with zeros to | length precision if necessary. The sign and exponent of the first operand are | unchanged. | | same_quantum(self, /, other, context=None) | Test whether self and other have the same exponent or whether both are NaN. | | This operation is unaffected by context and is quiet: no flags are changed | and no rounding is performed. As an exception, the C version may raise | InvalidOperation if the second operand cannot be converted exactly. | | scaleb(self, /, other, context=None) | Return the first operand with the exponent adjusted the second. Equivalently, | return the first operand multiplied by 10**other. The second operand must be | an integer. | | shift(self, /, other, context=None) | Return the result of shifting the digits of the first operand by an amount | specified by the second operand. The second operand must be an integer in | the range -precision through precision. The absolute value of the second | operand gives the number of places to shift. If the second operand is | positive, then the shift is to the left; otherwise the shift is to the | right. Digits shifted into the coefficient are zeros. The sign and exponent | of the first operand are unchanged. | | sqrt(self, /, context=None) | Return the square root of the argument to full precision. The result is | correctly rounded using the ROUND_HALF_EVEN rounding mode. | | to_eng_string(self, /, context=None) | Convert to an engineering-type string. Engineering notation has an exponent | which is a multiple of 3, so there are up to 3 digits left of the decimal | place. For example, Decimal('123E+1') is converted to Decimal('1.23E+3'). | | The value of context.capitals determines whether the exponent sign is lower | or upper case. Otherwise, the context does not affect the operation. | | to_integral(self, /, rounding=None, context=None) | Identical to the to_integral_value() method. The to_integral() name has been | kept for compatibility with older versions. | | to_integral_exact(self, /, rounding=None, context=None) | Round to the nearest integer, signaling Inexact or Rounded as appropriate if | rounding occurs. The rounding mode is determined by the rounding parameter | if given, else by the given context. If neither parameter is given, then the | rounding mode of the current default context is used. | | to_integral_value(self, /, rounding=None, context=None) | Round to the nearest integer without signaling Inexact or Rounded. The | rounding mode is determined by the rounding parameter if given, else by | the given context. If neither parameter is given, then the rounding mode | of the current default context is used. | | ---------------------------------------------------------------------- | Class methods defined here: | | from_float(f, /) from builtins.type | Class method that converts a float to a decimal number, exactly. | Since 0.1 is not exactly representable in binary floating point, | Decimal.from_float(0.1) is not the same as Decimal('0.1'). | | >>> Decimal.from_float(0.1) | Decimal('0.1000000000000000055511151231257827021181583404541015625') | >>> Decimal.from_float(float('nan')) | Decimal('NaN') | >>> Decimal.from_float(float('inf')) | Decimal('Infinity') | >>> Decimal.from_float(float('-inf')) | Decimal('-Infinity') | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | imag | | real
d = Decimal('15.700')
print(d)
d2 = d.normalize()
print(d2)
15.700 15.7
d = Decimal('6.00')
print(d)
d2 = d.normalize()
print(d2)
6.00 6
d == d2
True
d2 = d # d의 기존 버전을 d2에 저장
d = d.normalize() # 이제 d는 정규화되었다.
d2 == d
True
d2 is d
False
d = Decimal('15.0')
d.as_tuple()
DecimalTuple(sign=0, digits=(1, 5, 0), exponent=-1)
d = Decimal((0, (3, 1, 4), -2))
print(d)
3.14
import decimal
decimal.getcontext()
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])
money_amount = Decimal('1.99')
from decimal import Decimal
total = Decimal('0.00')
while True:
s = input('Enter amount in dollars and cents (#.##): ')
if not s:
break
d = Decimal(s)
d = round(d, 2)
total += d
print('The sum of all these amounts is:', total)
Enter amount in dollars and cents (#.##): 1 Enter amount in dollars and cents (#.##): 3.00 Enter amount in dollars and cents (#.##): 4.50 Enter amount in dollars and cents (#.##): 33.003 Enter amount in dollars and cents (#.##): 12.404 Enter amount in dollars and cents (#.##): The sum of all these amounts is: 53.90
from decimal import Decimal
class Money():
def __init__(self, v = '0', units = 'USD'):
self.dec_amt = Decimal(v)
self.units = units
m1 = Money('0.10')
print(m1.dec_amt, m1.units)
0.10 USD
print(m1)
<__main__.Money object at 0x0000028E43F6CBB0>
from decimal import Decimal
class Money():
def __init__(self, v = '0', units = 'USD'):
self.dec_amt = Decimal(v)
self.units = units
def __str__(self):
s = str(self.dec_amt) + ' ' + self.units
return s
m1 = Money('5.01', 'CAD')
print(m1)
5.01 CAD
from decimal import Decimal
class Money():
def __init__(self, v = '0', units = 'USD'):
self.dec_amt = Decimal(v)
self.units = units
def __str__(self):
s = str(self.dec_amt) + ' ' + self.units
return s
def __repr__(self):
s = ('Money(' + str(self.dec_amt) + ' ' + self.units + ')')
return s
m2 = Money('0.10')
print(m2)
m2
0.10 USD
Money(0.10 USD)
from decimal import Decimal
class Money():
'''통화 클래스
Decimal 값과 통화 단위를 함께 저장한다.
객체를 더할 때, 통화 단위가 다르면 환율을 반영한다.
'''
exch_dict = {
'USDCAD': Decimal('0.75'), 'USDEUR': Decimal('1.16'),
'CADUSD': Decimal('1.33'), 'CADEUR': Decimal('1.54'),
'EURUSD': Decimal('0.86'), 'EURCAD': Decimal('0.65')
}
def __init__(self, v = '0', units = 'USD'):
self.dec_amt = Decimal(v)
self.units = units
def __str__(self):
s = str(self.dec_amt) + ' ' + self.units
return s
def __repr__(self):
s = ('Money(' + str(self.dec_amt) + ' ' +
str(self.units) + ')')
return s
def __add__(self, other):
'''통화 더하기 함수.
2개의 통화 객체를 더한다.
두 번째 통화가 다른 통화 단위를 갖고 있다면,
두 값을 더하기 전에 환율이 반영되어야 한다.
소수 두 번째 자리로 반올림을 한다.
'''
if self.units != other.units:
r = Money.exch_dict[self.units + other.units]
m1 = self.dec_amt
m2 = other.dec_amt * r
m = Money(m1 + m2, self.units)
else:
m = Money(self.dec_amt + other.dec_amt, self.units)
m.dec_amt = round(m.dec_amt, 2)
return m
us_m = Money('1', 'USD')
ca_m = Money('1', 'CAD')
print(us_m + ca_m)
1.75 USD
from decimal import Decimal
# 통화 클래스 정의문을 이 곳에 넣거나, import 하기 바란다.
def money_calc():
'''통화 더하기 계산기
빈 문자열을 입력하기 전까지, 통화 객체 나열을 입력 받는다.
빈 문자열이 입력되면, 전체 합계를 출력한다.
'''
n = 0
while True:
s = input('Enter money value: ')
s = s.strip()
if not s:
break
a_list = s.split() # Split into amt, units.
d = a_list[0]
if len(a_list) > 1:
m = Money(d, a_list[1])
else:
m = Money(d)
if n == 0:
amt = m
else:
amt += m
n += 1
print('Total is', amt)
money_calc()
Enter money value: 1.05 Enter money value: 2.00 CAD Enter money value: 1.5 EUR Enter money value: 1.00 Enter money value: 2.5 CAD Enter money value: Total is 7.16 USD
money_calc()
Enter money value: 1.50 CAD Enter money value: 1.75 CAD Enter money value: 2.00 USD Enter money value: 1.00 USD Enter money value: Total is 7.24 CAD
from decimal import Decimal
class Money():
'''통화 클래스
Decimal 값과 통화 단위를 함께 저장한다.
객체를 더할 때, 통화 단위가 다르면 환율을 반영한다.
'''
default_curr = 'USD'
exch_dict = {
'USDCAD': Decimal('0.75'), 'USDEUR': Decimal('1.16'),
'CADUSD': Decimal('1.33'), 'CADEUR': Decimal('1.54'),
'EURUSD': Decimal('0.86'), 'EURCAD': Decimal('0.65')
}
def __init__(self, v = '0', units = ''):
self.dec_amt = Decimal(v)
if not units:
self.units = Money.default_curr
else:
self.units = units
def __str__(self):
s = str(self.dec_amt) + ' ' + self.units
return s
def __repr__(self):
s = ('Money(' + str(self.dec_amt) + ' ' +
str(self.units) + ')')
return s
def __add__(self, other):
'''통화 더하기 함수.
2개의 통화 객체를 더한다.
두 번째 통화가 다른 통화 단위를 갖고 있다면,
두 값을 더하기 전에 환율이 반영되어야 한다.
소수 두 번째 자리로 반올림을 한다.
'''
if self.units != other.units:
r = Money.exch_dict[self.units + other.units]
m1 = self.dec_amt
m2 = other.dec_amt * r
m = Money(m1 + m2, self.units)
else:
m = Money(self.dec_amt + other.dec_amt, self.units)
m.dec_amt = round(m.dec_amt, 2)
return m
from decimal import Decimal
# 통화 클래스 정의문을 이 곳에 넣거나, import 하기 바란다.
def money_calc():
'''통화 더하기 계산기
빈 문자열을 입력하기 전까지, 통화 객체 나열을 입력 받는다.
빈 문자열이 입력되면, 전체 합계를 출력한다.
'''
n = 0
while True:
s = input('Enter money value: ')
s = s.strip()
if not s:
break
a_list = s.split() # Split into amt, units.
d = a_list[0]
if len(a_list) > 1:
m = Money(d, a_list[1])
else:
m = Money(d)
if n == 0: # 첫 번째 항목이 입력되면
amt = m # amt를 만든다!
Money.default_curr = m.units
else:
amt += m
n += 1
print('Total is', amt)
money_calc()
Enter money value: 1.0 CAD Enter money value: 2.05 Enter money value: .95 Enter money value: 2 Enter money value: Total is 6.00 CAD
money_calc()
Enter money value: 2.0 CAD Enter money value: -1 Enter money value: 10 USD Enter money value: 5.01 Enter money value: -5.01 Enter money value: Total is 14.30 CAD
from decimal import Decimal
class Money(Decimal):
def __new__(cls, v, units='USD'):
return super(Money, cls).__new__(cls, v)
def __init__(self, v, units='USD'):
self.units = units
m = Money('0.11', 'USD')
print(m, m.units)
0.11 USD
from fractions import Fraction
fr1 = Fraction(1, 2)
fr2 = Fraction(2, 4)
fr3 = Fraction(100/200)
print('The fractions are %s, %s, & %s.' % (fr1, fr2, fr3))
The fractions are 1/2, 1/2, & 1/2.
if fr1 == fr2 and fr2 == fr3:
print('They are all equal!')
They are all equal!
if fr1 == fr2 == fr3:
print('They are all equal!')
They are all equal!
fr1 = Fraction(5)
print(fr1)
5
fr1 = Fraction(0.5)
print(fr1)
1/2
fr2 = Fraction(0.01)
print(fr2)
5764607523034235/576460752303423488
fr2 = Fraction('0.01')
print(fr2)
1/100
fr2 = Fraction(0.01).limit_denominator(1000)
print(fr2)
1/100
fr1 = Fraction(1, 2)
fr2 = Fraction(1, 3)
fr3 = Fraction(5, 12)
print(fr1 + fr2 + fr3)
5/4
fr1 = Fraction(1, 100)
print(fr1, 'times 50 =', fr1 * 50)
1/100 times 50 = 1/2
fr1 = Fraction('1/7')
print(fr1)
fr1 += Fraction('3/4')
print(fr1)
1/7 25/28
fr1 = Fraction('100/300')
print('numerator is', fr1.numerator)
print('denominator is', fr1.denominator)
numerator is 1 denominator is 3
from fractions import Fraction
total = Fraction('0')
while True:
s = input('Enter fraction (press ENTER to quit): ')
s = s.replace(' ', '') # 빈 칸이 있는 경우 제거한다.
if not s:
break
total += Fraction(s)
print('The total is %s.' % total)
Enter fraction (press ENTER to quit): 2 Enter fraction (press ENTER to quit): 1 Enter fraction (press ENTER to quit): 1/2 Enter fraction (press ENTER to quit): 1/3 Enter fraction (press ENTER to quit): -3 Enter fraction (press ENTER to quit): The total is 5/6.
z = 2.5 + 1.0j
z
(2.5+1j)
print('Real part is %s and imaginary part is %s.' % (z.real, z.imag))
Real part is 2.5 and imaginary part is 1.0.
z = complex(5.7, 10)
z
(5.7+10j)
print('Real part is %s and imaginary part is %s.' % (z.real, z.imag))
Real part is 5.7 and imaginary part is 10.0.
print(2j * 3j)
(-6+0j)
z = 2j * 3j
print(type(z.imag))
<class 'float'>
z = 0 + 2j * 0 + 3j
z
3j
z = 3j
print(z.real)
0.0
z = 2 + 0j
print(z)
print(z.real, z.imag)
(2+0j) 2.0 0.0
z = complex(3.5) # 가능하다. z.imag는 0이 될 것이다.
x = float(z) # 지원하지 않는다!
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-68-15b406c96149> in <module> 1 z = complex(3.5) # 가능하다. z.imag는 0이 될 것이다. ----> 2 x = float(z) # 지원하지 않는다! TypeError: can't convert complex to float
x = z.real # 이 것은 가능하다.
(6 + 3j) * (4 + 2j)
(18+24j)