How to program natural log in matlab

3 visualizaciones (últimos 30 días)
Josh
Josh el 25 de Nov. de 2013
Editada: John D'Errico el 26 de Nov. de 2013
I'm trying to write a Matlab function that will compute the natural log for any input within limits I have set. I'm considering the Taylor series expansion of f(x)=ln(1+x). Where the series is only converges for -1< x <=1. I'm also using E<10^-6 for convergence criterion. I wrote a program but its not running correctly. Any suggestions? Thank you in an advance for your help!
  2 comentarios
Walter Roberson
Walter Roberson el 25 de Nov. de 2013
What behavior do you observe instead of it "running correctly" ?
Josh
Josh el 25 de Nov. de 2013
The values it gives me are inaccurate.

Iniciar sesión para comentar.

Respuestas (1)

John D'Errico
John D'Errico el 26 de Nov. de 2013
Editada: John D'Errico el 26 de Nov. de 2013
You can learn a vast amount by reading what I did in my HPF toolbox, although there is no need for you to write a complete class to do the work. HPF uses series approximations, along with various range reduction schemes for all of the special functions I wrote. There I show how I compute logs that are accurate to many thousands of digits if desired.
Section 4.2 of HPFMod2.pdf describes the tricks I used in computation of the natural log. Find HPF here:
As an example...
log(hpf(2,100))
ans =
0.6931471805599453094172321214581765680755001343602552541206800094933936219696947156058633269964186875
And for comparison to the symbolic toolbox:
vpa(log(sym(2)),100)
ans =
0.6931471805599453094172321214581765680755001343602552541206800094933936219696947156058633269964186875
Some points to note:
You don't need to use a series to compute the log for all values of x, but only a restricted range, since you have various identities. For example, here is a simple one.
log(e*x) = log(e) + log(x) = 1 + log(x)
log(x/e) = -log(e) + log(x) = -1 + log(x)
So, if x is greater than sqrt(e), you can always divide by e repeatedly until x is not. Likewise, if x is less than 1/sqrt(e), you can always multiply by e until it is in the interval [1/sqrt(e),sqrt(e)].
So you might use a while loop to deal with x outside of the interval of interest.
exp(1/2)
ans =
1.64872127070013
exp(-1/2)
ans =
0.606530659712633
This is a reasonably small range to deal with. Once you get x into that interval, then a series approximation will do reasonably well. You can do a bit more of course, as I show in the pdf.

Categorías

Más información sobre Exponents and Logarithms en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by