0

I am trying to use the newton method but it seems I did some logical errors, can anyone help me pls ?

This program will use Newton's Method to approximate the minimum amount of graphene needed to for the company to break even on any given day.

#include <iostream>
#include <iomanip>
#include <math.h>
#include <cmath>

using namespace std;
void getStartingGuess(double&);
void calcRoots(double&);
double calcProfits(double);
double calcDerivative(double);

int main()
{
    double initialVal;
    getStartingGuess(initialVal);
    calcRoots(initialVal);
}

void getStartingGuess(double& initialVal)
{
    cout << "Enter a positive initial value: ";
    cin >> initialVal;
    if (initialVal < 0)
    {
        cout << "Invalid value, please re-enter:";
        cin >> initialVal;
    }
}

void calcRoots(double& initialVal)
{
    double profit, profitderiv, estimate;
    {
        for (int i = 1; i <= 5; ++i)
        {
            profit = calcProfits(initialVal);
            profitderiv = calcDerivative(initialVal);
            estimate = initialVal - (profit) / (profitderiv);
            cout << fixed << setprecision(3);
            cout << "#Iteration #" << i << ":" << estimate << endl;
            initialVal = estimate;
        }
        cout << "The final approximation is : " << estimate;
    }
}

double calcProfits(double initialVal)
{
    double profit;
    profit = -1000 + 2 * initialVal - (3 * pow(initialVal, 2 / 3));
    return profit;
}

double calcDerivative(double initialVal)
{
    double profitderiv;
    profitderiv = 2 - (2 / pow(initialVal, 1 / 3));
    return profitderiv;
}

Output:

Enter a positive initial value: 2
#Iteration #1:inf
#Iteration #2:nan
#Iteration #3:nan
#Iteration #4:nan
#Iteration #5:nan
The final approximation is : nan
Process returned 0 (0x0)   execution time : 4.398 s
Press any key to continue.

I'm looking for help to find my logical errors.

mch
  • 9,424
  • 2
  • 28
  • 42
Atsuki
  • 1
  • Welcome to Stack Overflow. Please read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). And please [edit] your question to improve it, like for example actually asking a question and telling us the problem you have with the code (please indent your code nicely and *consistently*). – Some programmer dude Nov 15 '22 at 08:29
  • [What is the behavior of integer division?](https://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division) and [Division of two numbers always returns an integer value](https://stackoverflow.com/questions/44973406/division-of-two-numbers-always-returns-an-integer-value). – Jason Nov 15 '22 at 08:33

1 Answers1

0

This is not correct

pow(initialVal,2/3)

2/3 equals 0 because it is integer division and so the result must be an integer. If you want two thirds then use

pow(initialVal,2.0/3.0)
john
  • 85,011
  • 4
  • 57
  • 81