asdas

Ruby code posted by asfd
created at 23 Nov 16:52

Edit | Back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
a=100000.0
r=0.06
p=10000.0
n=Math.log((-p)/(a*r-p),1+r) #formula for n, directly
p "n=#{n}" 
time= ( (1.0+r)**n * (a*r-p) +p)/r
p "Amount to pay after #{n} years : #{time}" 


a=100000.0
r=0.07754689530012998
#p=10000.0
n=15.725208543887753 #formula for n, directly
n=20
p=(a*r*(1.0+r)**n)/(((1.0+r)**n)-1)
puts p           



#file 5c.rb
def f(r)
  am=100000 # amount
  p = 10000 #payment/ year
  n=20    #years  
   # function for calculation p subtracted by itself to get a root 
   #for which we have root r such that f(r)=0
   # where r is ratio  >>>>
  (am*r*(1.0+r)**n)/(((1.0+r)**n)-1)-p
end
#used simplified Newton method for rootfinding
def newton_simple(init, epsilon)
  x = init
  d = f(x)/((f(x+f(x))-f(x))/f(x))
  while(d.abs > epsilon ) do
    x = x-d
    d = f(x)/((f(x+f(x))-f(x))/f(x))
  end
  return x
end


p newton_simple(0.6, 0.0000000000000001)
893 Bytes in 6 ms with coderay