2
\$\begingroup\$

My code calculates \$e^x\$ with series expansion. Is there any way to make it shorter and cleaner?

#lang racket
; evaluate e^x with series expansion, use first 10 terms.

(define (exp x)
  (letrec ([f1 (lambda (n cx cn)
                 ;(writeln (list n cx cn))
                 (if (>= n 10)
                     0
                     (+ (/ cx cn) (f1 (+ n 1) (* cx x) (* cn (+ n 1))))))])
    (+ 1 (f1 1 x 1))
    )
  )

(letrec ([N (read)]
         [rd (lambda (n)
               (unless (zero? n)
                       (define x (read))
                       (writeln (exp x)) (rd (- n 1))))])
  (rd N))
\$\endgroup\$
1
\$\begingroup\$

General Programming

  1. Using built the built in exponent function from racket/base and referencing Euler's Number from math/base would probably reduce the likelihood of bugs; increase speed; and allow programming at a higher level of abstraction.

  2. An alternative to read is the GUI function get-text-from-user in racket/gui/base.

Example Code

#lang racket

(require (only-in math/base
                  euler.0)
         (only-in racket/gui/base
                  get-text-from-user))

(define (get-power-of-e)
  (define x (string->number
             (get-text-from-user "Power of e"
                                 "provide exponent")))
  (expt euler.0 x))
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.