Mercurial > lasercutter
view src/clojure/contrib/generic/math_functions.clj @ 10:ef7dbbd6452c
added clojure source goodness
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Sat, 21 Aug 2010 06:25:44 -0400 |
parents | |
children |
line wrap: on
line source
1 ;; Generic interfaces for mathematical functions3 ;; by Konrad Hinsen4 ;; last updated May 5, 20096 ;; Copyright (c) Konrad Hinsen, 2009. All rights reserved. The use7 ;; and distribution terms for this software are covered by the Eclipse8 ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)9 ;; which can be found in the file epl-v10.html at the root of this10 ;; distribution. By using this software in any fashion, you are11 ;; agreeing to be bound by the terms of this license. You must not12 ;; remove this notice, or any other, from this software.14 (ns15 ^{:author "Konrad Hinsen"16 :doc "Generic math function interface17 This library defines generic versions of common mathematical18 functions such as sqrt or sin as multimethods that can be19 defined for any type."}20 clojure.contrib.generic.math-functions21 (:use [clojure.contrib.def :only (defmacro-)])22 (:require [clojure.contrib.generic.arithmetic :as ga]23 [clojure.contrib.generic.comparison :as gc]))25 (defmacro- defmathfn-126 [name]27 (let [java-symbol (symbol "java.lang.Math" (str name))]28 `(do29 (defmulti ~name30 ~(str "Return the " name " of x.")31 {:arglists '([~'x])}32 type)33 (defmethod ~name java.lang.Number34 [~'x]35 (~java-symbol ~'x)))))37 (defn- two-types [x y] [(type x) (type y)])39 (defmacro- defmathfn-240 [name]41 (let [java-symbol (symbol "java.lang.Math" (str name))]42 `(do43 (defmulti ~name44 ~(str "Return the " name " of x and y.")45 {:arglists '([~'x ~'y])}46 two-types)47 (defmethod ~name [java.lang.Number java.lang.Number]48 [~'x ~'y]49 (~java-symbol ~'x ~'y)))))51 ; List of math functions taken from52 ; http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html53 (defmathfn-1 abs)54 (defmathfn-1 acos)55 (defmathfn-1 asin)56 (defmathfn-1 atan)57 (defmathfn-2 atan2)58 (defmathfn-1 ceil)59 (defmathfn-1 cos)60 (defmathfn-1 exp)61 (defmathfn-1 floor)62 (defmathfn-1 log)63 (defmathfn-2 pow)64 (defmathfn-1 rint)65 (defmathfn-1 round)66 (defmathfn-1 sin)67 (defmathfn-1 sqrt)68 (defmathfn-1 tan)70 ;71 ; Sign72 ;73 (defmulti sgn74 "Return the sign of x (-1, 0, or 1)."75 {:arglists '([x])}76 type)78 (defmethod sgn :default79 [x]80 (cond (gc/zero? x) 081 (gc/> x 0) 182 :else -1))84 ;85 ; Conjugation86 ;87 (defmulti conjugate88 "Return the conjugate of x."89 {:arglists '([x])}90 type)92 (defmethod conjugate :default93 [x] x)95 ;96 ; Square97 ;98 (defmulti sqr99 "Return the square of x."100 {:arglists '([x])}101 type)103 (defmethod sqr :default104 [x]105 (ga/* x x))107 ;108 ; Approximate equality for use with floating point types109 ;110 (defn approx=111 "Return true if the absolute value of the difference between x and y112 is less than eps."113 [x y eps]114 (gc/< (abs (ga/- x y)) eps))