Learn R Programming

cwhmisc (version 6.0)

frac: Fractional part of number, continuous fractions

Description

Split off fractional part of a number, compute and evaluate continuous fractions.

Usage

int( x )
  frac(x,d)
  contfrac( x, depth = 13, f=floor ) 
  evalcfr( cf )
  toCFrac( x, depth=5)
  toCFrac2( x, depth=5)

Arguments

x
Real
d
If not missing, determines number of decimals after "."
f
function to use, normally 'floor', otherwise 'round' or 'trunc'
cf
Vector of integers representing the continued fraction of a real number
depth
Integer

Value

  • int integer part truncate towards 0. frac fractional part, if d is missing; else $round(10^d*fractional part)$, i.e. the fractional part as "integer" (rounded). contfrac Convert to simple continued fraction representation, $cf := a_1 + 1/(a_2 + 1/(a_3 ... ))$. evalcfr Evaluate simple continued fraction to corresponding real. toCFrac Build rational approximation num/den to x using forward continued fraction recursion to a depth of depth. Stopping criterion: either depth is reached, or abs(x - num/den) is increasing again. toCFrac2 same as toCFrac, but vectors of partial numerators and denominators are returned.

Examples

Run this code
int (c(0,pi,2*pi,30*pi))    # 0  3  6 94
frac(c(0,pi,2*pi,30*pi))    # 0.000000 0.141593 0.283185 0.247780
frac(c(0,pi,2*pi,30*pi), 3) # 0 142 283 248
(pcf <- contfrac(pi)) # 3, 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 2, (1)
## last integer incorrect due to rounding errors
evalcfr(pcf)-pi # 0
## To see the first approximants of pi, all of them famous:
for(ii in 1:15) {x<-toCFrac(pi,ii)
print(paste(ii,":",x$num,"/",x$den,"="))
print(paste(formatFix(x$num/x$den,15),", error = ",x$num/x$den-pi))}
# Note how the approximations taper off after depth 5:
# 10 3959189 / 1260249 =  3.141592653515298 -7.44955208631382e-11"
## Same, all at once:
F <- toCFrac2(pi,5)  # $num  3  22 333 355  $den  1   7 106 113
toCFrac( pi, 10 )  #

Run the code above in your browser using DataLab