import math, strutils, strformat import decimal import bignum #################################################################################################### # Utilities. proc format[T: DecimalType|Rat](val: T; intLen, fractLen: Positive): string = ## Format a decimal or a rational with "intLen" integer digits and "fractLen" ## fractional digits. let s = when T is DecimalType: ($val).split('.') else: ($val.toFloat).split('.') result = s[0].align(intLen) & '.' if s[1].len < fractLen: result.add s[1].alignLeft(fractLen, '0') else: result.add s[1][0..3} {vfloat[n]:>20.16f} {vdecimal[n].format(3, 16)} {vrational[n].format(3, 16)}" #################################################################################################### # Task 2. proc balance[T: float|DecimalType|Rat](): T = ## Return the balance after 25 years. result = when T is float: E - 1 elif T is DecimalType: exp(newDecimal(1)) - 1 else: newInt("17182818284590452353602874713526624977572470") / newInt("10000000000000000000000000000000000000000000") var n = when T is float: 1.0 else: 1 while n <= 25: result = result * n - 1 n += 1 echo "\nTask 2." echo "Balance after 25 years (float): ", (&"{balance[float]():.16f}")[0..17] echo "Balance after 25 years (decimal): ", balance[DecimalType]().format(1, 16) echo "Balance after 25 years: (rational): ", balance[Rat]().format(1, 16) #################################################################################################### # Task 3. const A = 77617 B = 33096 proc rump[T: float|DecimalType|Rat](a, b: T): T = ## Return the value of the Rump's function. let C1 = when T is float: 333.75 elif T is Rat: newRat(333.75) else: newDecimal("333.75") let C2 = when T is float: 5.5 elif T is Rat: newRat(5.5) else: newDecimal("5.5") result = C1 * b^6 + a^2 * (11 * a^2 * b^2 - b^6 - 121 * b^4 - 2) + C2 * b^8 + a / (2 * b) echo "\nTask 3" let rumpFloat = rump(A.toFloat, B.toFloat) let rumpDecimal = rump(newDecimal(A), newDecimal(B)) let rumpRational = rump(newRat(A), newRat(B)) echo &"f({A}, {B}) float = ", rumpFloat echo &"f({A}, {B}) decimal = ", rumpDecimal.format(1, 16) echo &"f({A}, {B}) rational = ", rumpRational.format(1, 16)