emmi
Posts: 42
Joined: Fri Jan 26, 2018 10:07 am

negative number in C++ code is giving problems

Thu Feb 22, 2018 8:43 am

Hello,

in my C++ code the line

Code: Select all

double Ulight = 1.3 / (1 - exp(-time_difference/(R*C)));
is giving problems. I have worked out now that the problem is with the minus in front of time_difference. I used the minus from the number block on my keyboard to type it.
R and C are global constants (double), 220 and 1 respectively. The time_difference (long int) is measured by the program just before it gets to this calculation. It measured values around 34 (should be higher, but that is another issue), so Ulight should come to something like 9.078. But because of the minus I get a -inf.
I tried

Code: Select all

double x = -time_difference/(R*C)
double y = time_difference/(R*C)
for trouble shooting. I get
x= 1.95226e+07
y = 0.154545

Does anyone have a clue why this happens and a piece of advice how to get the program working?
Thanks!

User avatar
PeterO
Posts: 4214
Joined: Sun Jul 22, 2012 4:14 pm

Re: negative number in C++ code is giving problems

Thu Feb 22, 2018 8:56 am

Very odd !

Please post a complete example program that demonstrates this behaviour because I think there must be something else going on to cause this and without seeing all of your code it is impossible to tell what is causing this strange behaviour.

PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),Aeromodelling,1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

emmi
Posts: 42
Joined: Fri Jan 26, 2018 10:07 am

Re: negative number in C++ code is giving problems

Thu Feb 22, 2018 9:26 am

This is the function that is misbehaving:

Code: Select all

//insolation measurement by U of PV module
double measure_light()
{
        wiringPiSetup();
        //drain voltage from capacitor
        pinMode(0, OUTPUT);
        digitalWrite (0, 0);
        delay(10000);

        long unsigned int start_time;
        long unsigned int time_difference;
        struct timespec gettime_now;

        clock_gettime(CLOCK_REALTIME, &gettime_now);
        start_time = gettime_now.tv_nsec;       //get ns value

        pinMode(0, INPUT);

        do
        {
                clock_gettime(CLOCK_REALTIME, &gettime_now);
                time_difference = (gettime_now.tv_nsec - start_time) / 1000;    //get µs value
                cout << time_difference << endl;
        } while (digitalRead(0)==0 && time_difference <= 25000);

        if(digitalRead(0)==1)
        {cout << "pin is HIGH\n";}
 	//drain voltage from capacitor
        pinMode(0, OUTPUT);
        digitalWrite (0, 0);
        delay(5000);
        cout << "Measured time [µs]: " << time_difference << endl;

        double Ulight;

        if(time_difference < 20000)
        {
                //Uo = Ut / (1 - e^(-t/(C*R)))
                Ulight = 1.3 / (1 - exp(-time_difference/(R2*C))); 	
                double n = (R2*C);								//the following lines were for troubleshooting only
                double o = (time_difference/(R2*C));
                double p = exp(-time_difference/(R2*C));
                double q = (1 - exp(-time_difference/(R2*C)));
                cout  << n << endl << o << endl << p << endl << q << endl;
                cout << "The current voltage of the PV panel is " << Ulight << " Volts.\n";
        }

        else
        {
                Ulight = 1.3;
                cout << "The current voltage of the PV panel is " << Ulight << " Volts or less.\n";
        }

        return Ulight;

};
And the output I get on the screen is

Code: Select all

35
Measured time [µs]: 35
220
0.159091
inf
-inf
The current voltage of the PV panel is -0 Volts.

emmi
Posts: 42
Joined: Fri Jan 26, 2018 10:07 am

Re: negative number in C++ code is giving problems

Thu Feb 22, 2018 9:32 am

As that might (or might not) be relevant as well, these are the libraries included in the header:

Code: Select all

#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string>
#include <fstream>
#include <math.h>
#include <time.h>
#include <wiringPi.h>

using namespace std;
I also included float.h just now to check if it makes a difference, it does not.

User avatar
RaTTuS
Posts: 10005
Joined: Tue Nov 29, 2011 11:12 am
Location: North West UK

Re: negative number in C++ code is giving problems

Thu Feb 22, 2018 9:33 am

long unsigned int start_time;
long unsigned int time_difference;

try signed if your going to have negatives
How To ask Questions :- http://www.catb.org/esr/faqs/smart-questions.html
WARNING - some parts of this post may be erroneous YMMV

1QC43qbL5FySu2Pi51vGqKqxy3UiJgukSX
Covfefe

emmi
Posts: 42
Joined: Fri Jan 26, 2018 10:07 am

Re: negative number in C++ code is giving problems

Thu Feb 22, 2018 9:35 am

RaTTuS wrote: long unsigned int start_time;
long unsigned int time_difference;

try signed if your going to have negatives
The time_difference itself should be positive though. I included the unsigned because before I got negative values for time_difference which should not be possible if the system was working correctly.

EDIT: Okay, I tried it out, seems to be working. Thanks!

User avatar
RaTTuS
Posts: 10005
Joined: Tue Nov 29, 2011 11:12 am
Location: North West UK

Re: negative number in C++ code is giving problems

Thu Feb 22, 2018 9:57 am

emmi wrote:
Thu Feb 22, 2018 9:35 am
....h should not be possible if the system was working correctly.
....
always code for when things should not be possible...

the amount of times I've had defensive code if () { //this should not be possible } come out with code that should never be there -
sanitise everything ,
always check

it will point to some other place where you have got something unexpected....
How To ask Questions :- http://www.catb.org/esr/faqs/smart-questions.html
WARNING - some parts of this post may be erroneous YMMV

1QC43qbL5FySu2Pi51vGqKqxy3UiJgukSX
Covfefe

jahboater
Posts: 2782
Joined: Wed Feb 04, 2015 6:38 pm

Re: negative number in C++ code is giving problems

Thu Feb 22, 2018 10:46 am

+1

You could try assert() for example:

assert( time_difference >= 0 );

see: man assert

Daniel Gessel
Posts: 21
Joined: Sun Dec 03, 2017 1:47 am

Re: negative number in C++ code is giving problems

Fri Feb 23, 2018 3:08 pm

Try casting time_difference to double before negating. Probably, negating an unsigned produces an unsigned (which is positive - likely the two’s compliment of the original value) and then converted to a double for the division.

Using unsigned values with math requires extra care... It’s often a pain.

jahboater
Posts: 2782
Joined: Wed Feb 04, 2015 6:38 pm

Re: negative number in C++ code is giving problems

Fri Feb 23, 2018 3:43 pm

Daniel Gessel wrote:
Fri Feb 23, 2018 3:08 pm
Probably, negating an unsigned produces an unsigned (which is positive - likely the two’s compliment of the original value)
Yes, it is defined in C (surprisingly) and does: ~n + 1

LdB
Posts: 773
Joined: Wed Dec 07, 2016 2:29 pm

Re: negative number in C++ code is giving problems

Fri Feb 23, 2018 4:59 pm

The problem is obvious and it has nothing to do with the negative .... R & C are integers or longints

Please do a refresher on C divison typecasts there is no reason the compiler would know to promote that to a float or double

time_difference/(R*C) =====> long int / (int * int)

The result of that is going to be a long int every single time ... its the C rule you asked it to do an integer division :-)

here try it .. guarantee you this gives zero on any C compiler

Code: Select all

double t = 1/(3*2);
You will read it the same way as above and say the answer should be 0.16666667 but you are wrong there is no reason C would know to promote the right hand side.

I have no doubt you wanted a float or a double but sorry the compiler isn't a mind reader

You want a double or float the its up to you to typecast the division as you have integer types.
I would typecast the numerator but it's equally valid to typecast the denominator C will then know what you are doing.

Code: Select all

double x = -(double)time_difference/(R*C);
double y = (double)time_difference/(R*C);

User avatar
PeterO
Posts: 4214
Joined: Sun Jul 22, 2012 4:14 pm

Re: negative number in C++ code is giving problems

Fri Feb 23, 2018 5:22 pm

LdB wrote:
Fri Feb 23, 2018 4:59 pm
The problem is obvious and it has nothing to do with the negative .... R & C are integers or longints
Read the first post in the thread ...
R and C are global constants (double), 220 and 1 respectively.
PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),Aeromodelling,1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

Daniel Gessel
Posts: 21
Joined: Sun Dec 03, 2017 1:47 am

Re: negative number in C++ code is giving problems

Fri Feb 23, 2018 5:25 pm

I thought I checked for R, C being ints in the posted code (didn’t see them defined) and OP stated they were doubles. I must not be seeing the code you found wher R & C are defined. My bad.

Daniel Gessel
Posts: 21
Joined: Sun Dec 03, 2017 1:47 am

Re: negative number in C++ code is giving problems

Fri Feb 23, 2018 5:31 pm

Possibly get some negative values because you are not accounting for seconds part of the tv struct here:

time_difference = (gettime_now.tv_nsec - start_time) / 1000;

You need to add tv_sec delta * 1,000,000 to get a proper micro second delta.

For timing, I use:

u64 nanoseconds()
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
return u64(ts.tv_sec) * 1000000000ULL + u64(ts.tv_nsec);
}

PiGraham
Posts: 3320
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: negative number in C++ code is giving problems

Fri Feb 23, 2018 6:12 pm

I See from your code you are subtracting two tv_nsec members. That's not reliable. The ns value is only a tiny part of the time and it wraps around every second. That means you will get a lot of negative values more or less at random.

You should compute both parts of the value to allow for the wrap-around of the fractional part.

The same issue applies to struct timeval, dicussed here: http://www.gnu.org/software/libc/manual ... apsed-Time

[edit] same point as post above while I was typing.

jahboater
Posts: 2782
Joined: Wed Feb 04, 2015 6:38 pm

Re: negative number in C++ code is giving problems

Fri Feb 23, 2018 6:21 pm

Mine is:

clock_gettime( CLOCK_MONOTONIC, &now );
return (uint64_t)now.tv_sec * 1000000000U + (uint64_t)now.tv_nsec;

Return to “C/C++”

Who is online

Users browsing this forum: No registered users and 6 guests