Haskell作业1(1)|实现分数的常用运算(2)|计算平方根的Newton-Raphson公式

一、实现分数的常用运算

module MyFraction where
import Test.QuickCheck
import Prelude hiding ((<*>))

type Fraction = (Integer, Integer)

ratplus :: Fraction -> Fraction -> Fraction
ratplus (a,b)(c,d)
	|a==0 =(c,d)
	|c==0 =(a,b)
	|otherwise =(div (a*d+b*c) ga , div (b*d) ga )
	where
	ga=gcd (a*d+b*c)(b*d)

ratminus :: Fraction -> Fraction -> Fraction
ratminus (a,b)(c,d)=
	(div (a*d-b*c) gb , div (b*d) gb )
	where
	gb=gcd (a*d-b*c)(b*d)

rattimes :: Fraction -> Fraction -> Fraction
rattimes (a,b)(c,d)
	|a*c==0 =(0,1)
	|otherwise =(div (a*c) gc , div (b*d) gc )
	where
	gc=gcd (a*c)(b*d)

ratdiv :: Fraction -> Fraction -> Fraction
ratdiv (a,b)(c,d)= 
	(div (a*d) gd , div (b*c) gd )
	where
	gd=gcd (a*d)(b*c)

ratfloor :: Fraction -> Integer
ratfloor (a,b)=
	div a b

ratfloat :: Fraction -> Float
ratfloat (a,b)=
	fromInteger a / fromInteger b

rateq :: Fraction -> Fraction -> Bool
rateq (a,b)(c,d)=
	if ((a*d-b*c) == 0) then True else False

--↓定义新的运算符

(<+>) :: Fraction -> Fraction -> Fraction
(a,b) <+> (c,d) = 
	ratplus (a,b) (c,d)

(<->) ::  Fraction -> Fraction -> Fraction
(a,b) <-> (c,d) = 
	ratminus (a,b) (c,d)

(<*>) ::  Fraction -> Fraction -> Fraction
(a,b) <*> (c,d) = 
	rattimes (a,b) (c,d)

(>) ::  Fraction -> Fraction -> Fraction
(a,b) > (c,d) = 
	ratdiv (a,b) (c,d)

(<==>) ::  Fraction -> Fraction -> Bool
(a,b) <==> (c,d) = 
	rateq (a,b) (c,d)

--↑定义新的运算符

--↓四则运算函数的性质(交换律

prop_change :: Fraction -> Fraction -> Bool
prop_change (a,b) (c,d)
	|b*d == 0 =True
	|otherwise	 =ratplus(a,b)(c,d) == ratplus (c,d)(a,b) &&rattimes(a,b)(c,d) == rattimes (c,d)(a,b)


--↑四则运算函数的性质(交换律

--↓解决四则运算优先级问题

infixl 7 <*>,>
infixl 6 <+>,<->
infixl 5 <==>

--


二、计算平方根的Newton-Raphson公式

module NewtonRaphson where

--类型
squareroot2 :: Float -> Integer -> Float
squareroot :: Float -> Float -> Integer -> Float
sqrtSeq :: Float -> Float -> [Float]
squareroot' :: Float -> Float -> Float -> Float
square_root2 :: [Float] -> Float -> Float

--表达式(?)
squareroot2 x n = 
	if n<=0 then x else squareroot2 ((x+2/x)/2) (n-1)

squareroot r x n = 
	if n<=0 then x else squareroot r ((x+r/x)/2) (n-1)

sqrtSeq r x = 
	[squareroot r x y|y<- [1..]]

squareroot' r x e =
	square_root2 (sqrtSeq r x) e

square_root2 (y:ys) e = 
	if ((head ys)-y<=e && y-(head ys)<=e) then y else  square_root2 ys e




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章