How to program natural log in matlab

조회 수: 4 (최근 30일)
Josh
Josh 2013년 11월 25일
편집: John D'Errico 2013년 11월 26일
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
Walter Roberson
Walter Roberson 2013년 11월 25일
What behavior do you observe instead of it "running correctly" ?
Josh
Josh 2013년 11월 25일
The values it gives me are inaccurate.

댓글을 달려면 로그인하십시오.

답변 (1개)

John D'Errico
John D'Errico 2013년 11월 26일
편집: John D'Errico 2013년 11월 26일
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.

카테고리

Help CenterFile Exchange에서 Exponents and Logarithms에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by