# L-24 MCS 471 Mon 17 October 2022 : difforward.jl # Program to experiment with forward differentiation on exp(x), # with plotting instructions for a log plot. # using Plots using Printf # the forward difference formula : fwdexp(x, h) = (exp(x+h) - exp(x))/h """ Prompts the user for a value for x, the initial value for h, the number of approximations, and then applies the forward difference formula, each time dividing h by 10. Suggested values for x, h, and the number of approximations are 1, 0.1, and 16. """ function main() print("Give a value for x : ") line = readline(stdin) xval = parse(Float64, line) print("Give an upper bound for h : ") line = readline(stdin) hval = parse(Float64, line) print("Give the number of approximations : ") line = readline(stdin) nbr = parse(Float64, line) exact = exp(xval) strexact = @sprintf("%.16e", exact) println("Approximating $strexact :") for i=1:nbr approx = fwdexp(xval, hval) err = abs(exact - approx) strhval = @sprintf("%.3e", hval) strapprox = @sprintf("%.16e", approx) strexact = @sprintf("%.16e", exact) strerr = @sprintf("%.3e", err) println(" $strhval $strapprox $strerr") hval = hval/10.0 end end main() # we make a logplot of the errors : # aloghvals = [abs(log(10,10.0^(-p))) for p=1:16] # alogerror = [log(10,abs(fwdexp(1.0, 10.0^(-p)) - exp(1.0))) for p=1:16] # scatter(aloghvals, alogerror, marker=(:red), label="log(10, errors)") # savefig("forwarderrors.png")