S
S
SPLATHER2019-01-09 01:21:42
C++ / C#
SPLATHER, 2019-01-09 01:21:42

What piece of code to add to calculate the logarithm with a given accuracy?

Here is the code in Visual Studio 17.
#include
#include
#include
double sum = 0;
double x;
using namespace std;
int main(void)
{
setlocale(LC_ALL, ".1251");
cout << "Enter x: ";
cin >> x;
if (x >= 0 && x <= 2)
{
x -= 1;
for (int i = 1; i < 5000; i += 2)
{
sum += (pow(x, i) / (double)i - pow(x, i + 1) / (double)(i + 1) );
}
cout<<(sum);
}
else if (x > 2)
{
x = (x / (x - 1));
for (int i = 1; i < 1000; i++)
{
sum += 1.0 / (i*pow(x, i));
}
cout<<(sum);
}
else
{
cout << ("Wow, wow. How long has the sum of the series started with negative numbers?");
}
}
If I did the right thing at all, then the logarithm is calculated here using the series expansion. Even if you do not help directly, then at least hint in which direction to step.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2019-01-09
@longclaps

for (int i = 1; i < 5000; i += 2) {
    sum += (pow(x, i) / (double)i - pow(x, i + 1) / (double)(i + 1));
    // смотрите, здесь у вас скомбинированы слогаемые разного знака.
    // но, если их растащить, получится сходящийся знакопеременный ряд,
    // а погрешность по модулю не превышает второе слогаемое.
}

// как-то так
double first, second = 1;
for (int i = 1; abs(second) > epsilon; i += 2) {
    first  = pow(x, i) / (double)i;
    second = pow(x, i + 1) / (double)(i + 1);
    sum += first - second;
}

update
Chota answer recklessly plus, and at least someone realizes that the series is alternating only at x>0.
For x<0, i.e. for the logarithm argument (1+х)<1, you should calculate the logarithm (as the sum of the series) for the reciprocal, and change the sign, of course.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question