Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1.  
  2.  
  3. ;;
  4. ;; Preamble: Lisp prerequisits
  5. ;;
  6.  
  7. ;; These two lines sets the number of binary digits used to represent a float
  8. ;; in Lisp. This is necessary because you'll be working with tiny numbers
  9. ;; TL;DR ignore these two lines
  10. (setf (EXT:LONG-FLOAT-DIGITS) 35000)
  11. (setf *read-default-float-format* 'long-float)
  12.  
  13. ;; This method rounds a number to a certain precision
  14. ;; It takes two arguments: the number to round and the number of digits to
  15. ;; round in decimals
  16. ;;
  17. ;; Example: (roundToPrecision 10.0044 3) -> 10.004
  18. (defun roundToPrecision (number precision)
  19. (let
  20. ((p (expt 10 precision)))
  21. (/ (round (* number p)) p)
  22. )
  23. )
  24.  
  25. ;;
  26. ;; Exercise
  27. ;;
  28.  
  29. ;; Exercise
  30. ;; Your task is to implement the Gauss-Legendre algorithm for calculating pi
  31. ;; and extract 10.000 (ten thousand) digits
  32.  
  33. (write-line "Pi opgave")
  34. (setf an 1)
  35. (setf bn 0.709219858) ; 1/√2 = 1/1.41 = 0.709219858
  36. (setf tn 0.25) ; 1/4 = 0.25
  37. (setf pn 1)
  38.  
  39. (defun nextA (an bn)
  40. "Documentation for nextA."
  41. (/ (+ an bn) 2)
  42. )
  43.  
  44. (defun nextT (an pn tn bn)
  45. "Documentation for nextT."
  46. (- tn (* pn (expt (- an (nextA an bn)) 2)))
  47. )
  48.  
  49. (defun nextB (an bn)
  50. "Documentation for nextB."
  51. (sqrt (* an bn))
  52. )
  53.  
  54. (defun nextP (pn)
  55. "Documentation for nextP."
  56. (* 2 pn)
  57. )
  58.  
  59. (defun calcPi (an bn tn pn piOld)
  60. "Documentation for calcPi."
  61. (let (
  62. (aNew (nextA an bn))
  63. (bNew (nextB an bn))
  64. (tNew (nextT an pn tn bn))
  65. (pNew (nextP pn))
  66. )
  67. (let
  68. ((piNew (roundToPrecision (/ (expt (+ aNew bNew) 2) (* 4 tNew)) 15)
  69. )
  70. )
  71. (if
  72. (= (roundToPrecision piNew 100) (roundToPrecision piOld 100))
  73. piNew
  74. (calcPi aNew bNew tNew pNew piNew)
  75. )
  76. )
  77. ))
  78.  
  79. (write (coerce (calcPi 1L0 (/ 1L0 (sqrt 2L0)) (/ 1L0 4L0) 1L0 1L0) 'long-float))
  80.  
  81. ;; Gauss-Legendre algorithm on Wikipedia
  82. ;; https://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_algorithm
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement