from decimal import * def exp(x): """Return e raised to the power of x. Result type matches input type. >>> print exp(Decimal(1)) 2.718281828459045235360287471 >>> print exp(Decimal(2)) 7.389056098930650227230427461 >>> print exp(2.0) 7.38905609893 >>> print exp(2+0j) (7.38905609893+0j) """ getcontext().prec += 2 i, lasts, s, fact, num = 0, 0, 1, 1, 1 while s != lasts: lasts = s i += 1 fact *= i num *= x s += num / fact getcontext().prec -= 2 return +s def ln(k): """logaritmo naturale con il metodo delle tangenti di Newton usare in input un Decimal la funzione di cui si cerca lo zero e' f(x)=e^x-k dato che ln(k)=x; trovando la derivata e applicando x1=x0-f(x0)/f'(x0) per le approssimazioni successive si risolve il problema a partire dal calcolo di e^x con la funzione precedente""" getcontext().prec += 2 x0=k/256 #Decimal(128) x1=x0-1+k/exp(x0) c=getcontext().prec-3 i=1 while abs(x0-x1)> Decimal(str(10**-c)): #x0<>x1: x0=x1 x1=x0-1+k/exp(x0) i += 1 getcontext().prec -= 2 print 'num. iterazioni', i #print x0, x1 return +x1 #getcontext().prec = 40 #for j in range(20): print 10,'\t',ln(Decimal(10)) print