[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Math Time!

Todd

5/2/2007 2:28:00 AM


--- James Edward Gray II <james@grayproductions.net>
wrote:

> On May 1, 2007, at 7:22 PM, Ari Brown wrote:
>
> > So today I tried to write a program which would
> print out, say,
> > 1000 digits of pi.
>
> ruby -rbigdecimal -rbigdecimal/math -e 'include
> BigMath; digits =
> 1000; puts
> "3."+BigDecimal.PI(digits).to_s[3,digits]'
>
> > Ok, so to the point. How do I tell Ruby to print a
> value (.to_f) to
> > a certain number of integers?
>
> printf "%.20f", flt
>
> > .to_f(1000)? And also, how do I write tan, cos,
> sin, etc. in Ruby?
>
> Math.tan(num) # etc.
>
> James Edward Gray II

Or you could do it the hard way (yes, reinventing the
wheel is one of my faults)

####
# we'll just assume all computed variables
# are BigDecimals

def pi( precision )
(0..precision).inject(0) { |sum, i| i*=4; sum +
1.0/(i+1) - 1.0/(i+3) } * 4
end

puts pi( 1000 )

####
# 900 times the age of the universe
# later on my slow system ...

# 3.14159...
# this series takes my system about 6 seconds
# just to get to 3.14159 (precision = 1_000_000)
# and goes up about a factor of 10 for each additional
# digit
#
# for 1000 digits, you would need a precision
# value of 1 followed by 1000 0's (1e1000)


####
# cos() converges almost immediately

def fact( i )
return i == 0 ? 1 : fact( i - 1 ) * i
end

def cos( angle, precision )
(0..precision).inject(0) { |sum, i| i*=4; sum +
angle**i/fact(i) - angle**(i+2)/fact(i+2) }
end

puts cos( 1.0, 3 )

# 0.540302305868092

require 'mathn'
puts Math::cos(1.0)

# 0.54030230586814

__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail...