Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Dawncloack
Nov 26, 2007
ECKS DEE!
Nap Ghost
Hello friends

I keep writing my little program to solve the knapsack problem and, as before, I've run into a problem that's confusing me.

Here:
(ValuesForCounter is an int*, countOfElements and MaxCombinationsTried, ints, everything else is float or float*)

code:

do

    CombiFunc(valuesForCounter, countOfElements); // this is a combinatorial counter. 
Suffice to say that it's a counter where no combination of numbers is ever repeated, 
since for the purposes of this program 121, 211 and 112 are the same for me.

        for (weeCounter = 0; weeCounter <= countOfElements; weeCounter++)
        {
            std::cout<<valuesForCounter[weeCounter]<<" // "; // for me to check the results in conjunction with ***** below

            placeHolder += pricesOfElements[valuesForCounter[weeCounter]];
        }
        std::cout<<"result= "<<placeHolder<<std::endl; // *****

    if (placeHolder < (targetValue + 0.01) && placeHolder > (targetValue - 0.01) && valuesForCounter[0] <= countOfElements)
        {
        maxNum++; // number of results found
        saver(); //saves the results
        }

    weeCounter = 0;
    placeHolder = 0;
    resultsTried++;
    }while(valuesForCounter[maxCombinationsTried] < 1); //all values start at 0.
just fyi, maxCombinationsTried is an int and in represents the largest divider between the target value and the lowest non-zero price. I use to determine how many combinations to check, since I want to have all results but not check more combinations than necessary.

Here's my problem: Every time that targetValue is an even number, this little program works like a charm. Everytime it's odd, I get different kinds of errors.

It's doubly odd since, when I use XKCD values, it works perfectly. I get this problem when I use the rest of the program, whose point is to let the user input any collection of values then solve the problem.

It's true that when I use XKCD values I know exactly the values of CountOfElements, TargetValue yadda yadda, so I wonder if I made a mistake in the user input part and it doesn't count something accurately, and that reflects on the calculation of the results. But I can't figure out what for the life of me.

Thanks in advance, and ask for clarifications if needed. You can also make fun of me, if my programming "skillz" call for it.

Dawncloack fucked around with this message at 16:31 on Dec 13, 2012

Adbot
ADBOT LOVES YOU

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

So I'm playing around with Boost's ASIO and was wondering if anyone had any suggestions on how I should pass large numbers of strings from one process to another (on the same network).

I'm thinking sockets and maybe multiple receiving ports?

If that's the way to go, are Socket Iostreams the right thing to use?

If not, maybe Google's Protocol Buffers or something else?

Thanks

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!
I was curious how I might approach a problem that looks at first glance like it's good for Boost's signal library. I want listen for some kind of event, but during the subscription process, I wanted to in some fashion put some restrictions. Like, the event may first for 10 different, dynamic, types of things, and maybe I only care about 3 of them. I could create my own subscription model, but then I'm dealing with everything myself, like automatically unsubscribing. Is there anything in Boost to try to make this simpler?

Max Facetime
Apr 18, 2009

roomforthetuna posted:

The guy said I should have used 'log' rather than walking down the up to 10 digits it would take to get to the start of the number.

Coming briefly back to this, does there exist an unsigned integer value such that the mathematical real number value of it's log10 is greater than the closest integer but the closest IEEE floating-point value is less than the closest integer, or vice versa?

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Win8 Hetro Experie posted:

Coming briefly back to this, does there exist an unsigned integer value such that the mathematical real number value of it's log10 is greater than the closest integer but the closest IEEE floating-point value is less than the closest integer, or vice versa?

Assuming your unsigned integer and your IEEE floating-point value have the same number of bits, no there is not.

This is easy to see once you realize that a float can represent integers exactly up to the number of bits in the mantissa, which the log10 of the largest unsigned integer still falls into.

Max Facetime
Apr 18, 2009

I was thinking that too, but then I read Wikipedia and there's stuff like:

Wikipedia posted:

The IEEE 754 standard requires the same rounding to be applied to all fundamental algebraic operations, including square root and conversions, when there is a numeric (non-NaN) result. It means that the results of IEEE 754 operations are completely determined in all bits of the result, except for the representation of NaNs. ("Library" functions such as cosine and log are not mandated.)

...

Conversions to integer are not intuitive: converting (63.0/9.0) to integer yields 7, but converting (0.63/0.09) may yield 6. This is because conversions generally truncate rather than round. Floor and ceiling functions may produce answers which are off by one from the intuitively expected value.

So I just tried it, here are the most interesting results:

pre:
tests: floor(log10(value))+1 floor(log10(value)+1) floor(1+log10(value))
testing around 10
...
testing around 100000000000000
testing around 1000000000000000
999,999,999,999,998:	16	16	16
999,999,999,999,999:	16	16	16
testing around 10000000000000000
9,999,999,999,999,939:	16	17	17
...
9,999,999,999,999,978:	16	17	17
9,999,999,999,999,979:	17	17	17
...
testing around 100000000000000000
99,999,999,999,999,900:	18	18	18
...
testing around 1000000000000000000
999,999,999,999,999,900:	19	19	19
The three tests are implemented as follows:

Java code:
  private static int calculateAnswer1(long value) {
    return (int) (Math.floor(Math.log10(value)) + 1);
  }

  private static int calculateAnswer2(long value) {
    return (int) Math.floor(Math.log10(value) + 1);
  }

  private static int calculateAnswer3(long value) {
    return (int) Math.floor(1 + Math.log10(value));
  }
Yeah it's in Java and there's no 32bit float versions of floor and log10 library functions, so results in C and C++ may be different.

shrughes
Oct 11, 2008

(call/cc call/cc)

Win8 Hetro Experie posted:

Coming briefly back to this, does there exist an unsigned integer value such that the mathematical real number value of it's log10 is greater than the closest integer but the closest IEEE floating-point value is less than the closest integer, or vice versa?

If n is the closest integer to x and x is greater than n and n is less than 2^53 or 2^24 (for doubles and floats, respectively), then no. All such integers n are IEEE floating-point values.

Your experiment in your latest post does not contradict my or tef's replies. The fact that you have log10 in there is of no interest. What you're observing is the effect of taking a number that is slightly less than 16 and adding 1 to it. If that number is the nearest floating point value, just underneath 16, adding 1 to it will produce 17 exactly because going to the other side of a power of two will chop off that last bit of precision (and it rounded up).

So, what you're observing is the log10 function producing that value, the nearest floating point value less than 16.

Note that for shorter and longer numbers, you won't get this effect. Add 1 to the nearest floating point value less than 17, and you'll get the nearest floating point value less than 18. That's because the distance of those values from the integer is the same. It only happens for powers of two.

And it only happens when you get 16-digit numbers or larger because the derivative of the log10(x) function is 1/(x*log(10)) and 1/10^16 is pretty close to 1/2^52. That's where log10(x) starts getting to be the adjacent value or just getting rounded up to the integer.

shrughes fucked around with this message at 04:09 on Dec 18, 2012

Max Facetime
Apr 18, 2009

shrughes posted:

If n is the closest integer to x and x is greater than n and n is less than 2^53 or 2^24 (for doubles and floats, respectively), then no. All such integers n are IEEE floating-point values.

Right, these values were what I was trying find from Wikipedia earlier.

shrughes posted:

Your experiment in your latest post does not contradict my or tef's replies.

:crossarms:

Anyway, I didn't intend the experiment as contradicting anyone, but to explore the follow-up question "given that the number of digits in an unsigned integer is exactly representable using floating point, does that mean it's safe to use the log10 function to calculate it?"

Sylink
Apr 17, 2004

edit: solved my problam.

Sylink fucked around with this message at 19:35 on Dec 18, 2012

The Gripper
Sep 14, 2004
i am winner

Sylink posted:

edit: solved my problam.
This question actually made me remember a question I had and forgot.

I almost exclusively use C++ in Visual Studio so this hasn't come up previously, but with MinGW some libraries like this one require me to compile anything linked with it with g++ -static or it just crashes the hell out with libstdc++-6.dll errors.

I'm sure there's a good explanation for it and it's not some kind of broken system fluke, but it's something I'd like to know because currently if it happens I just shrug and add -static to the command line and pretend it never happened. I'm obviously not doing any production-ready work or I'd have asked a lot earlier.

The Gripper fucked around with this message at 20:27 on Dec 18, 2012

UraniumAnchor
May 21, 2006

Not a walrus.
Two unrelated questions.

First, I'm using boost to parse a JSON file into a ptree. The JSON file is about 9 megabytes. On an iOS device this is less than a second on anything remotely modern. However, even on a Note 2 on Android this can take upwards of 9-10 seconds, and this happens on every Android device I've tested. My only guess is that using the standard allocator is very slow for some reason and parsing out a JSON file uses a lot of small allocations. However, there's a binary ptree format that I can use and the equivalent file takes less than a second to parse, even on Android. Any ideas on what might be causing the slowdown before I start trying to take apart the allocator? I haven't had any luck getting a profiler to work.

Secondly, is there a way to make a type constructable from "nullptr" and ONLY nullptr, not any other pointer? I know nullptr will decay to any pointer type without any special help, but does it have its own type? This one is more of a curiosity.

b0lt
Apr 29, 2005

UraniumAnchor posted:


Secondly, is there a way to make a type constructable from "nullptr" and ONLY nullptr, not any other pointer? I know nullptr will decay to any pointer type without any special help, but does it have its own type? This one is more of a curiosity.

nullptr_t

Mr. Tetsuo
Jun 6, 2011

And just once, before I die, I'd like to be Supreme Overlord of Earth. So rebel, my little ones, and conquer the planet!
Kinda of a heretic question I think, but I'll try it anyway: are the Scott Meyers books (Effective/More effective C++/STL) still worth reading? There is an Amazon promotion that has the kindle version of all 3 at about half the price of the paper books (55 vs 100):

http://www.amazon.com/Effective-Digital-Collection-Programming-ebook/dp/B008E30L9A/

awesmoe
Nov 30, 2005

Pillbug

ilikelettuce posted:

Kinda of a heretic question I think, but I'll try it anyway: are the Scott Meyers books (Effective/More effective C++/STL) still worth reading? There is an Amazon promotion that has the kindle version of all 3 at about half the price of the paper books (55 vs 100):

http://www.amazon.com/Effective-Digital-Collection-Programming-ebook/dp/B008E30L9A/
Even at that price, I'd wait till they're updated for c++11. They're great books but there's a lot of stuff there that's just out of date.

Mr. Tetsuo
Jun 6, 2011

And just once, before I die, I'd like to be Supreme Overlord of Earth. So rebel, my little ones, and conquer the planet!

awesmoe posted:

Even at that price, I'd wait till they're updated for c++11. They're great books but there's a lot of stuff there that's just out of date.

That was my concern. Thanks, I think I'll just wait then.

The Gripper
Sep 14, 2004
i am winner

ilikelettuce posted:

Kinda of a heretic question I think, but I'll try it anyway: are the Scott Meyers books (Effective/More effective C++/STL) still worth reading? There is an Amazon promotion that has the kindle version of all 3 at about half the price of the paper books (55 vs 100):

http://www.amazon.com/Effective-Digital-Collection-Programming-ebook/dp/B008E30L9A/
Don't bother buying any technical ebooks from Amazon because for what you're gaining with the price-cut you're losing with their poo poo being hosed as all hell. You're way better off just buying paperbacks.

Seriously, even the PDF versions of technical books on Amazon are just broken, you are restricted in what you can do even down to the copy/paste level, and as of June this year the PDF editions couldn't even be used on devices without a full-edition Adobe Reader because they require an internet connection and active Amazon account to load (they're blank, otherwise).

They're completely fine if all you want to do is view them on your Kindle and nothing else, but are way too crippled at least for me to ever bother with again.

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

The Gripper posted:

Don't bother buying any technical ebooks from Amazon because for what you're gaining with the price-cut you're losing with their poo poo being hosed as all hell. You're way better off just buying paperbacks.

Seriously, even the PDF versions of technical books on Amazon are just broken, you are restricted in what you can do even down to the copy/paste level, and as of June this year the PDF editions couldn't even be used on devices without a full-edition Adobe Reader because they require an internet connection and active Amazon account to load (they're blank, otherwise).

They're completely fine if all you want to do is view them on your Kindle and nothing else, but are way too crippled at least for me to ever bother with again.
You can't copy and paste from a paperback or view it on other devices either. :confused:

I'm sure the non-PDF format ones having hosed up diagrams and layouts and stuff is a thing, but the inability to copy-paste or view on other devices is a weird thing to complain about at the same time as recommending paper.

The Gripper
Sep 14, 2004
i am winner

roomforthetuna posted:

You can't copy and paste from a paperback or view it on other devices either. :confused:

I'm sure the non-PDF format ones having hosed up diagrams and layouts and stuff is a thing, but the inability to copy-paste or view on other devices is a weird thing to complain about at the same time as recommending paper.
I guess that particular one is just an expectation, not an actual downside to their digital books.

Personally I buy ebooks for the convenience of being able to just load it up on my laptop/whatever wherever I am, and Amazons restrictions tend to break that for me. Frank Luna's DX11 book for example won't display anything unless I'm logged into Amazon with Internet Explorer, because it connects to Amazon to authenticate every time it's opened.

icantfindaname
Jul 1, 2008


So I have this basic file i/o program, but when it runs I get a segmentation fault (and also a compiler warning about exit()). I'm running x64 Ubuntu. What exactly is the problem? Both in.list and out.list exist and are in the same directory as the binary.

code:
#include <stdio.h>

int main(int argc, char **argv)
{
        FILE *ifp, *ofp;
        char outputFilename[] = "out.list";
        char username[9];
        int score;

        ifp = fopen("in.list", "r");

        if (ifp == NULL)
        {
                printf("Can't open input file in.list!\n");
                exit(1);
        }

        ofp = fopen("out.list", "w");

        if (ofp = NULL)
        {
                fprintf(stderr, "Can't open output file %s!\n", outputFilename);
                printf("DONGS");
                exit(1);
        }

        while (fscanf(ifp, "%s %d", username, &score) != EOF)
        {
                fprintf(ofp, "%s %d\n", username, score+10);
        }

        fclose(ofp);
        fclose(ifp);

        return 0;
}
edit: Including stdlib fixes the error, but the segmentation fault is still there.

icantfindaname fucked around with this message at 22:23 on Dec 22, 2012

FamDav
Mar 29, 2008
The compiler warning for exit is because you aren't including stdlib.h

b0lt
Apr 29, 2005

icantfindaname posted:

code:
        if (ofp = NULL)

covener
Jan 10, 2004

You know, for kids!

icantfindaname posted:

code:
        if (ofp = NULL)

==

icantfindaname
Jul 1, 2008



Ah, that would do it. Thanks.

Vanadium
Jan 8, 2005

The problem is you aren't compiling with enough warnings. :sun:

foo.c:20:9: warning: suggest parentheses around assignment used as truth value [-Wparentheses]

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Add CFLAGS="-Wall -Werror" to your ~/.bashrc now.

And always compile with "make foo" rather than "gcc -o foo foo.c"

Vanadium
Jan 8, 2005

-O0 -g -pedantic -Wall -Wextra -Wwrite-strings -Wcast-qual -Wno-missing-field-initializers -Wstrict-overflow=5 -Wcast-align -Winit-self -Wunused-local-typedefs -Wuninitialized -Wmaybe-uninitialized -Wsuggest-attribute=pure -Wsuggest-attribute=const -Wsuggest-attribute=noreturn -Wundef -Wunsafe-loop-optimizations -Wconversion -Wlogical-op -Wredundant-decls -Winline -Wdisabled-optimization -Wunused-macros -ansi -Wdeclaration-after-statement -Wbad-function-cast -Wstrict-prototypes -Wmissing-prototypes -Wmissing-declarations -Wnested-externs -Waggregate-return -Wno-unused-parameter -Wjump-misses-init -Wold-style-definition


... what?

Vanadium
Jan 8, 2005

I don't write a lot of C code, but when I do, I want to be told about as many stupid mistakes as possible before I show it to other people!!

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Vanadium posted:

-Waggregate-return

Why?

Hughlander
May 11, 2005

Vanadium posted:

-O0 -g -pedantic -Wall -Wextra -Wwrite-strings -Wcast-qual -Wno-missing-field-initializers -Wstrict-overflow=5 -Wcast-align -Winit-self -Wunused-local-typedefs -Wuninitialized -Wmaybe-uninitialized -Wsuggest-attribute=pure -Wsuggest-attribute=const -Wsuggest-attribute=noreturn -Wundef -Wunsafe-loop-optimizations -Wconversion -Wlogical-op -Wredundant-decls -Winline -Wdisabled-optimization -Wunused-macros -ansi -Wdeclaration-after-statement -Wbad-function-cast -Wstrict-prototypes -Wmissing-prototypes -Wmissing-declarations -Wnested-externs -Waggregate-return -Wno-unused-parameter -Wjump-misses-init -Wold-style-definition


... what?

Go -Weverything or go home. (Clang only.)

Vanadium
Jan 8, 2005


I haven't seen a lot of C code that intentionally returns a struct by value, I dunno.

Volte
Oct 4, 2004

woosh woosh
For one thing it may implicitly alter the calling convention of the function, since the return value can't go into a register anymore.

chglcu
May 17, 2007

I'm so bored with the USA.
edit: Ignore. Responded to older post while on medication.

Edison was a dick
Apr 3, 2010

direct current :roboluv: only

-std=c99 or go home.
unless you need to compile it with Visual Studio, in which case I offer my condolences

Ulio
Feb 17, 2011


how would I write something that prints the value of EOF?

Posting Principle
Dec 10, 2011

by Ralp

Ulio posted:

how would I write something that prints the value of EOF?

EOF is a macro defined in <stdio.h>. It's a negative integer, but the exact value is implementation specific. Since you should already know how to print an integer, you should be able to work out how you can print EOF.

b0lt
Apr 29, 2005

Edison was a dick posted:

-std=c99 or go home.
unless you need to compile it with Visual Studio, in which case I offer my condolences

-std=c11 :colbert:

FearIt
Mar 11, 2007
Hello again CoC,

For the last couple of days I have been trying to take a screenshot on OSX using C++. Google has let me to try X11 and OpenGL implementations But in both of these attempts my XGetImage / glReadPixels data is coming back as all zero.

Does anybody know why this might be happening? All I'm trying to do is capture the rgb of the desktop in a reasonable time ( without writing / reading to a file ).

nielsm
Jun 1, 2009



FearIt posted:

Hello again CoC,

For the last couple of days I have been trying to take a screenshot on OSX using C++. Google has let me to try X11 and OpenGL implementations But in both of these attempts my XGetImage / glReadPixels data is coming back as all zero.

Does anybody know why this might be happening? All I'm trying to do is capture the rgb of the desktop in a reasonable time ( without writing / reading to a file ).

Why are you involving X11?
When you are on OSX you should be using AGL, Apple's OpenGL framework, which is not related to X11 at all. But OpenGL is the right thing to be doing for this.
I'm pretty sure I've actually seen a sample program that does exactly this (screen capture) on Apple's developer site.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
You want to use CGWindowListCreateImage:

C code:
CGImageRef screenPixelsImage = CGWindowListCreateImage(CGRectInfinite, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageDefault);
That gives you a CGImage, which you can manipulate to get the pixels.

Adbot
ADBOT LOVES YOU

FearIt
Mar 11, 2007
nielsm - I was just trying to get something working and those were the first two places on the google path.

nielsm, suspicious - Thanks for your suggestions, I'll give them both a shot and see what I can get working.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply