math.scm 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. (library (math)
  2. (export PI
  3. sine*
  4. make-sine-func
  5. float->scaled-truncated-integer)
  6. (import (except (rnrs base) let-values vector-for-each)
  7. (only (guile)
  8. lambda* λ
  9. inexact->exact
  10. truncate))
  11. (define PI (* 4 (atan 1.0)))
  12. (define modify-argument
  13. (λ (func modifier)
  14. (λ (x)
  15. (func
  16. (modifier x)))))
  17. (define offset
  18. (λ (func shift)
  19. (modify-argument func
  20. (λ (x) (+ x shift)))))
  21. (define modify-result
  22. (λ (func modifier)
  23. (λ (x)
  24. (modifier (func x)))))
  25. (define amplify-*
  26. (λ (func amplification)
  27. (modify-result func
  28. (λ (x) (* x amplification)))))
  29. (define amplify-+
  30. (λ (func amplification)
  31. (modify-result func
  32. (λ (x) (+ x amplification)))))
  33. (define sine*alt
  34. (lambda* (x #:key (amplitude 1) (frequency 1) (phase-offset 0))
  35. ((amplify-*
  36. (offset (modify-argument sin (λ (arg) (* 2 PI frequency arg)))
  37. phase-offset)
  38. amplitude)
  39. x)))
  40. ;; idea:
  41. ;; modify result? -- amplify
  42. ;; modify argument? -- change freq., phase offset
  43. (define sine*
  44. (lambda* (x #:key (amplitude 1) (frequency 1) (phase-offset 0))
  45. "Calculate the value of a modified sine function. The sine
  46. function is modified by amplitude, frequency and phase
  47. offset. The defaults make a sine function, which rotates a
  48. full circle in 1 second."
  49. ;; Multiplying by the amplitude make the resulting
  50. ;; value of the sine function smaller or bigger, in
  51. ;; effect changing the amplitude.
  52. (* amplitude
  53. ;; Use the standard sine function, but modify its
  54. ;; argument.
  55. (sin
  56. ;; Adding to the argument of the sine function
  57. ;; will give the result of a bigger or smaller
  58. ;; input value, in effect shifting the along the
  59. ;; x-axis.
  60. (+ (*
  61. ;; Multiplying by 2*pi changes the sine function
  62. ;; so that it goes full circle in [0;1]. This is
  63. ;; so, because usually the since function would
  64. ;; only do 1/2pi of circle within [0;1].
  65. 2 PI
  66. ;; Multiplying with the frequency makes it so,
  67. ;; that frequency full circles are in [0;1].
  68. frequency
  69. ;; x is the actual argument for the modified
  70. ;; sine function.
  71. x)
  72. phase-offset)))))
  73. (define make-sine-func
  74. (lambda* (#:key (amplitude 1) (frequency 1) (phase-offset 0))
  75. "Make a sine function, given the amplitude, frequency and
  76. phase offset."
  77. (λ (x)
  78. (sine* x
  79. #:amplitude amplitude
  80. #:frequency frequency
  81. #:phase-offset phase-offset))))
  82. (define float->scaled-truncated-integer
  83. (λ (num scale)
  84. (inexact->exact
  85. (truncate
  86. (* num scale))))))