0

I wrote a function to calculate the value of the function y = f(x) = x^3 + 2*x^2 - 4x + 1.

But then I realise that the result when using the function vs the result when not using the function is different at some value of x. Here's my code:

#include<iostream>
#include<cmath>

using namespace std;

int function(int x) {
    int y= pow(x, 3) + 2*x*x - 4*x + 1;
    return y;
};

int main(void) {
    for(int i = -5; i < 10; i++) cout << function(i) << std::endl;

    for(int i = -5; i < 10; i++) cout << pow(i, 3) + 2*i*i - 4*i+1 << ' ';

    return 0;
}

And the result is:

-53 -15 3 9 6 1 0 9 34 81 155 265 414 609 856
-54 -15 4 9 6 1 0 9 34 81 156 265 414 609 856

I'm so confused right now. Please help.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
Trung Kiên
  • 135
  • 1
  • 8
  • 1
    The function call truncates the return value to an integer. Don't use floating point calculations if you want exact integer results. – dxiv Jan 05 '21 at 19:24
  • 4
    `pow(x,3)` is a floating point function, it's not a integer function. Floating point arithmetic is inaccurrate so the differences you are seeing are problably due to rounding errors, and maybe subtly different code inside and outside your function. Change `pow(x,3)` to `x*x*x` (and the same for `i`) and the difference should go away. – john Jan 05 '21 at 19:24

2 Answers2

1

Within the function you get the result as an integer

int y= pow(x,3) + 2*x*x - 4*x +1;

while within main you are outputting the result as a floating number

cout << pow(i, 3) + 2*i*i - 4*i+1 << ' ';

The function pow in the global namespace is declared like

double pow(double x, double y);

So for the integer result there is used truncation of a floating number.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
-3

I Think There is issue with your compiler because I have compiled that code & got same result. Please Check Attached Picture. Attached PictureThanks.

eitzaz shah
  • 104
  • 4
  • You are supposed to get the same result. His question is about the first number on both calls, where one is -53 and the other -54 – vmp Jan 05 '21 at 19:27
  • 1
    Welcome to StackOverflow. Unfortunately, "I can't reproduce the problem" does not qualify as an answer here. When you reach 50 reputation, you will able to comment questions. – Yksisarvinen Jan 05 '21 at 19:28
  • im using VSCode with MinGW https://imgur.com/a/G6Sd4Xw – Trung Kiên Jan 05 '21 at 19:34