Reputation: 1030
Why does this algorithm not produce a triangle output in C++ when it should?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double w = 1050;
double a = 1050*3;
double speed;
for(int x = 0; x <= 1050; x+=42)
{
speed = 42*((4*a)/w*abs((fmod((x-w/2),w))-w/2)*-1+w)/w;
cout << "x: " << x << " speed: " << speed << endl;
}
}
Produces:
x: 0 speed: -462
x: 42 speed: -441.84
x: 84 speed: -421.68
x: 126 speed: -401.52
x: 168 speed: -381.36
x: 210 speed: -361.2
x: 252 speed: -341.04
x: 294 speed: -320.88
x: 336 speed: -300.72
x: 378 speed: -280.56
x: 420 speed: -260.4
x: 462 speed: -240.24
x: 504 speed: -220.08
x: 546 speed: -199.92
x: 588 speed: -179.76
x: 630 speed: -159.6
x: 672 speed: -139.44
x: 714 speed: -119.28
x: 756 speed: -99.12
x: 798 speed: -78.96
x: 840 speed: -58.8
x: 882 speed: -38.64
x: 924 speed: -18.48
x: 966 speed: 1.68
x: 1008 speed: 21.84
x: 1050 speed: 42
https://rextester.com/NSI24628
The correct answer is https://docs.google.com/spreadsheets/d/1XiUgHs7QYOWqggjLup0Wsx-eo0R82xrelUTTDBlgNkE/edit?usp=sharing
Why is C++ producing a linear answer whereas a triangle function is expected?
Upvotes: 0
Views: 125
Reputation: 87944
Your formula expects the result of fmod((x-w/2),w)
to be in the range [0,w)
but it isn't. The actual range is (-w,w)
. If (x-w/2)
is negative then the result of fmod
will be negaitve.
The simple fix is to replace fmod((x-w/2),w)
with fmod((x+w/2),w)
which ensures the first parameter of fmod
is positive without changing the overall effect.
Upvotes: 4