• Welcome to the new Internet Infidels Discussion Board, formerly Talk Freethought.

The Programming Thread

Variable argument functions.

Neither cout nor printf() will print __int128 integers.

Not to worry, you can build your own printf(). I found the integer print function on the net when looking at __int128 numbers.

Writing a parser to parser a format string with arbitrary text and to handle number format display precision as printf() does would take some work. I put text in separate strings.

Code:
void print_int128(__int128 x) {
    // source -- https://codeforces.com/blog/entry/75044

    if (x < 0) {
        putchar('-');
        x = -x;
    }
    if (x > 9) print_int128(x / 10);
    putchar(x % 10 + '0');

}//print_int128()


void xprintf(const char *fmt, ...){

    va_list args;
    va_start(args, fmt);


     while (*fmt != '\0') {

        if(*fmt == 's') {
            string s = va_arg(args, string);
            cout<<s;

        }//if


        if(*fmt == 'd') {
            int n = va_arg(args, int);
            cout<<n;

        }//if

        if(*fmt == 'f') {
            double d = va_arg(args, double);
            cout<<d;
        }//if

        if(*fmt == 'k'){
            __int128 x = va_arg(args,__int128);
            print_int128(x);
         }

      if(*fmt == '\n') {
            cout<<endl;
      }//if

      ++fmt;
     }//while
    va_end(args);
}//xprintf()



int main()
{
    char format[20] = {"%s%d%s%f%s%k\n"};
    string s1 = "  int  ";
    string s2 = "  double  ";
    string s3 = "  int 128  ";
    int a =1234;
    double b = 1.234;
    __int128 c = 12345678;
    xprintf(format,s1,a,s2,b,s3,c);

    return 0;
}
 
I'm probably going to stop posting here. This may be my last post.

I discover a HUGE anamoly in the Gospel genealogy,
Hi I created a thread about that here:
 
Last edited:
I'm probably going to stop posting here. This may be my last post.

I discover a HUGE anamoly in the Gospel genealogy, of which the many Christian "scholars" on view with Google seem oblivious! It is an enigma or a puzzle, and I asked Infidels for help resolving it. Only one response, and it implied that any solution would just be a fiction anyway, and therefore of little interest. (Briefly, James is one of three principal disciples in BOTH Paul's writing AND the synoptic Gospels. BUT the latter is James ben Zebedee brother of John, while the former is ostensibly the Lord's brother AND also James ben Alphaeus. This latter James is sometimes called James the Just and sometimes James the Less. The synoptic Gospels repeatedly refer to "another Mary" attending the crucifixion. John calls her Jesus' mother but the synoptics call her mother of James and Joses ben Alphaeus. If Jesus' father really was Joseph (or Yahweh!) then James and Joses are his HALF-brothers. ... Another possible solution is that James ben Alphaeus was "the disciple Jesus loved" that "John" writes about, and became a stepbrother with the Lord's dying words.


I post in other threads as well. Call me childish but I smile when someone clicks Like, and am less happy when someone quotes me without a Like.

I was flabbergasted by the response I got from Politesse in a recent thread. If I do continue on, I'll avoid any further dialog with [whatever his pronoun].

In this thread, I thought it fun to post some one-liners that convert a uniform variate to some other type of random variable. As usual, no response. Perhaps you all were waiting for my corrections! :)

Here [corrected]:
#define MASK (MAXRAND >> 2)
double RUF(void)
{ return (random() & MASK | 1) / (double)(MASK+1); }

struct twodgaussian { double r, th; };
void rr_2dgauss(struct twodgaussian *p)
{ p->r = sqrt(log(RUF() * -2); p->th = RUF() * 2 * 3.141592653589; }

int rr_hispick(struct hphelper p[], int psiz)
{ double t = RUF() * psiz; return p[t]->ix[p[t]->thresh > t]; }

For the math nerd out there: WHY is it convenient (natural?) to return a variate over an actual bell-shape (2D manifold) rather than over the "bell curve", i.e. the cross-section of such a bell with a piece of paper?

rr_hispick() actually implements a very useful and oft-seen random selection. Huge kudos if you if you can write code to setup the hphelper array by reverse-engineering the one-liner.
:(

I'll miss you greatly if you disappear. I know we don't always see eye to eye, but I like you a lot.

If you do bugger off, let me know where I can find you so I can keep annoying you with (whatever).
 
Ok Swami, I'll bite.

Normal, Gaussian, and bell curve are all synonymous. You can look up the probability distribution equation. Don't know where a manifold comes into it.

What do you mean by a cross section of a flat 2d curve?

What do mean by initialize the arrays other than defining them?

It looks like RUFF creates a random fractional number. and 2dgaussian creates the normal distribution from the random numbers.

rr_hist[ick sounds like histogram.

Have no clue what hphelper is.

As usual in your posts it may be clear in your head but it is not clear in the post.
 
It's just another of my many perversions, but I've always been a fan of "nifty one-liners." Need to convert a Gregorian date to day of the week? Why use a loop if there's a nifty one-line macro!

I realize this is usually more perverse than practical. Most professional programmers will respond with something like "I'm just trying to make a dime, and you want me to fret for an hour about saving a line of code?? I think it's Swammi with the problem; he should increase his laxative dosage. Anyway I get paid for lines of code; why would I waste time reducing their number?"

But some "weird one-liners" accomplish things not otherwise easily done. Consider the following code. I hope detractors will actually take the time to read and ponder.

A PRNG typically returns an integral number (call it NBITS) of random bits, thus yielding an integer x in the range {0, 1, 2, ..., RAND_MAX } where RAND_MAX is an all-ones mask with NBITS number of 1's.
In the attached code we suppose the number of bits is 27; and the macro NB_TO_M(27) yields 0x7ffffff, i.e. RAND_MAX.

But in fact the spec defines RAND_MAX but does NOT define NBITS. What if you want NBITS as a compile-time constant? It's easy to turn NBITS into RAND_MAX, and the NB_TO_M macro shown below does that. But what about the vice versa? M_TO_NB ?

Code:
#include        <stdio.h>
#include        <stdlib.h>

#define         NBITS           27 // number of bits returned by random()
#define         MAXRAND         0x7ffffff
#define         NB_TO_M(nb)     (((unsigned long long)1 << (nb)) - 1)

// Do NOT try to understand the following arithmetic gibberish.
// Just know that IT WORKS !!!
#define         M_TO_NB(m)      \
        ((m) / ((m) % 255 + 1) / 255 % 255 * 8 + 7 - 100 / ((m) % 255 + 14))

int main(int argc, char **argv)
{

        int     nb;
        unsigned long long msk;

        for (nb = 0; nb < 64; nb++) {
                msk = NB_TO_M(nb);
                printf("%d %d\n", nb, M_TO_NB(msk));
        }

        exit(0);
}

Is the M_TO_NB one of the wackiest macros you've ever seen? :) Compile and run the above program to verify it magically does its chore for any 0 <= nb <= 63.

Anyway, it's the fact that I'm a fan of one-liners that led me to post some one-liners associated with generating random variables.

Ok Swami, I'll bite.

Normal, Gaussian, and bell curve are all synonymous. You can look up the probability distribution equation. Don't know where a manifold comes into it.

Yes. But note that the equation for a distribution does NOT automatically lead to the generator for a random variable over that distribution.
What do you mean by a cross section of a flat 2d curve?

The Gaussian curve f(x) is a 1-D distribution. A 2-D Gaussian is simply the distribution of PAIRS (x, y), where x and y are each drawn from the same 1-D Gaussian.

The 1-D Gaussian is visualized with a bell-shaped curve on a 2-D piece of paper. The 2-D Gaussian is visualized with a physical bell in 3-D space. (It seemed confusing to speak of a 2-D distribution represented in 3-D space; hence my mention of "2-D manifold.")

There is something very intriguing about the Gaussian curve. It is often easier to work with a 2-D Gaussian than a 1-D Gaussian. You see that in the rr_2dgaus() function I posted -- it yields TWO Gussian variates for the price of one. (And generating a SINGLE variate may be harder than generating TWO !! -- Ignoring the trivial approach of calling rr_2dgaus() and discarding one of the two variates it generates.

There's another, somewhat mystifying property of the 2-D Gaussian. When you call rr_2dgaus() you get the 2-D variate in polar coordinates. If you want 1-D variates you can get two via:

variate1 = p->r * cos(p->th);
variate2 = p->r * sin(p->th);

But variates are supposed to be independent of each other. How can they be independent if they're using the same inputs p->r and p->th? At first glance it may seem that there's something very wrong. But in fact the independence follows from separability.

BTW, these Gaussian variates all have mean = 0 and sd = 1. Tune them to suit via
(variate * sd + mean)

Steve? Anyone? Does this all make any sense? (Never mind difficult details like the 2D-Gaussian separability.) Is anything here interesting? Please answer; don't make me wish I'd just indulged in self-abuse rather than spending the time to compose this post. :)
 
Still don't see how the code in your post has any valuem and as usal you don't seem able to explain why.

A normal distribution can have non zero means. Look at the equation. The normalized variate has zero mean and a stAndard deviation of 1. If yOu do not understnd that then you really do not undertsnd and your polar coodrnates and 2d is just hand waving.



Your typical post. A moving goal post. This is why I don't usually reond to your posts.

Making it easier to read.

double ruf(void){
double k1,k2;
unsigned int mask = RAND_MAX>>2;
k1 = sqrt((double)((rand() & mask | 1) ));
k2 = (k1/(double)(mask + 1));
return k2;
}

Don't have a clue what you are trying to do. Shifting right twice is a an integer division by 4.

sqrt((double)((rand() & mask | 1) )) is ambiguous. You have to specify grouping for the logic.
sqrt((double)(((rand() & mas) | 1) )) or sqrt((double)((rand() & (mask | 1)) ));

Note that the compiler flags a warning ob the ambiguity. Also nesting built in function calls can lead to problems. The compiler parser may not always implement what yiou intend.

Did you mean rand() % mask + 1 instead of rand() & mask | 1 ?

I ran your code.Using your ruff() the resulting histogram is a negative exponential. Using a unfirm distribution results in a log normal distribution.

Your ruf() does not appear to be a uniform distribution. I checd my resits in C against Scilab using their random uniform distribution.

Code:
double ruf(void){
    double k1,k2;
    unsigned int mask = RAND_MAX>>2;
    k1 = sqrt((double)((rand() & mask | 1) ));
    k2 = (k1/(double)(mask + 1));
    return k2;
}

double ruf2(void){
    //uniform distribution  > 0  < 1
    return double(rand())/double(RAND_MAX + 1);
}

void rrgaus2d(struct gaus2d *p){
    p->r = sqrt(log(ruf()*-2.));
    p->th = ruf() * PI2;
}

int main()
{

    int n = 10000,i;
    double k[n];
    srand(unsigned (time(NULL)));


   for(int i = 0;i<n;i++){
     k[i] = sqrt(log(ruf2())*-2);;
    }
    //for(i=0;i<n;i++)printf("%f\n",ruf());
    FILE *ptr = fopen("data.txt","w");
    fprintf(ptr,"%d\n",n);
    for(i=0;i<n;i++)fprintf(ptr,"%.6f\n",k[i]);
    fclose(ptr);

return 0;
}
 
It's just another of my many perversions, but I've always been a fan of "nifty one-liners." Need to convert a Gregorian date to day of the week? Why use a loop if there's a nifty one-line macro
In webpages you need to do that sometimes so it’s easy to do it in PHP (code from ChatGPT)
PHP:
$date = '2023-05-05'; // The date you want to convert
$day_of_week = date('l', strtotime($date)); // 'l' stands for the full name of the day of the week

echo $day_of_week; // Outputs 'Friday'
Or in one line:
PHP:
echo date('l', strtotime('2023-05-05'));
 
Last edited:
C:
#include        <stdio.h>
#include        <stdlib.h>

#define         NBITS           27 // number of bits returned by random()
#define         MAXRAND         0x7ffffff
#define         NB_TO_M(nb)     (((unsigned long long)1 << (nb)) - 1)

// Do NOT try to understand the following arithmetic gibberish.
// Just know that IT WORKS !!!
#define         M_TO_NB(m)      \
        ((m) / ((m) % 255 + 1) / 255 % 255 * 8 + 7 - 100 / ((m) % 255 + 14))
In books like the Clean Coder they say code should be self-documenting - so you could have helpful function and variable names even if they are more than ten characters long. I'm not sure why you're using an unsigned long long.... it allows up to 18,446,744,073,709,551,615 and might be slower than a smaller integer type.
 
I am disappointed -- but should not be surprised -- that no one found anything interesting in my code. That's OK, What I do NOT like are the incorrect implications that my code is defective! :)

It's just another of my many perversions, but I've always been a fan of "nifty one-liners." Need to convert a Gregorian date to day of the week? Why use a loop if there's a nifty one-line macro
In webpages you need to do that sometimes so it’s easy to do it in PHP (code from ChatGPT)
Code:
$date = '2023-05-05'; // The date you want to convert
$day_of_week = date('l', strtotime($date)); // 'l' stands for the full name of the day of the week

If someone has already written a function to do XXX, of course one can invoke that function and it will be a one-liner that does XXX. Duh.
But somebody had to write that function! That somebody could be anyone who finds it FUN to write low-level code. It could be (and often was) me. (There's a variety of consumer devices circa 2000 that run code or hardware algorithms written or designed by me.)

I'm reminded of the time I tried to explain the power of Unix by pointing out that the rot13 service could be obtained in Unix with simply
tr n-zN-Za-mA-M a-mA-Mn-zN-Z​
I got a reply like "So what? Microsoft has the same thing: you just download rot13.exe."

Talk about missing the point!

C:
#include        <stdio.h>
#include        <stdlib.h>

#define         NBITS           27 // number of bits returned by random()
#define         MAXRAND         0x7ffffff
#define         NB_TO_M(nb)     (((unsigned long long)1 << (nb)) - 1)

// Do NOT try to understand the following arithmetic gibberish.
// Just know that IT WORKS !!!
#define         M_TO_NB(m)      \
        ((m) / ((m) % 255 + 1) / 255 % 255 * 8 + 7 - 100 / ((m) % 255 + 14))
In books like the Clean Coder they say code should be self-documenting - so you could have helpful function and variable names even if they are more than ten characters long. I'm not sure why you're using an unsigned long long.... it allows up to 18,446,744,073,709,551,615 and might be slower than a smaller integer type.
I did NOT obfuscate the code I delivered to customers, The code I post HERE at IIDB is often deliberately terse to be more challenging. The M_TO_NB macro is seldom if ever used, but seemed like an interesting example for a post about one-liners.

The reason I use long long is in case you apply the macro to such a 64-bit integer. Much code will use such integers, if only in the future. Why limit the utility of the macro?

As for "might be slower", the MAXRAND (or similar) argument provided to the macro will be a compile-time constant, so the invoked macro is a compile-time constant also. It will be computed ZERO times during execution. (Some scenarios will execute the macro ONCE during execution.)

Still don't see how the code in your post has any valuem and as usal you don't seem able to explain why.

A normal distribution can have non zero means. Look at the equation. The normalized variate has zero mean and a stAndard deviation of 1. If yOu do not understnd that then you really do not undertsnd and your polar coodrnates and 2d is just hand waving.

I tried to explain that the function returns a 2-D gaussian in polar coordinates. And that I wasn't trying to complicate needlessly, but rather that it's EASIER to compute the 2D gaussian variates (and in polar coordinates) than to calculate a 1-D variate. (Similarly sometimes integrating a 2D gaussian is easier than integrating a 1D!)
Your typical post. A moving goal post. This is why I don't usually reond to your posts.
Not responding would probably work well.

Making it easier to read.

double ruf(void){
double k1,k2;
unsigned int mask = RAND_MAX>>2;
k1 = sqrt((double)((rand() & mask | 1) ));
k2 = (k1/(double)(mask + 1));
return k2;
}
There's an unrelated sqrt that somehow got interjected into your version of my code.
sqrt((double)((rand() & mask | 1) )) is ambiguous. You have to specify grouping for the logic.

Wrong. C defines precedence, so the "grouping" here is defined. Most coders don't have a problem with (a*b*c + 3*f + d) and because useless parentheses become distracting, that expression is more readable than ((((a*b)*c)+(3*f))+d). Admittedly, most programmers haven't memorized all the precedences, and omitting the parentheses from ((rand() & mask) | 1) can be called obfuscation, Note that in the wrong-precedence version the "| 1" would have no effect. Thus the precedence can be immediately deduced by anyone who's forgotten it.

sqrt((double)(((rand() & mas) | 1) )) or sqrt((double)((rand() & (mask | 1)) ));

Note that the compiler flags a warning ob the ambiguity. Also nesting built in function calls can lead to problems. The compiler parser may not always implement what yiou intend.

"Nesting built in function calls can lead to problems", while perhaps not completely wrong, is confused. Code either does or does not comply with spec. Mine does.

I actually ensure that my code produces no warnings by default (gcc -W). Perhaps you use compiler flags that led to more stringent warnings. My experience is that "-W" flags possible real problems. If you prefer whining about parentheses, that's fine for you.

Did you mean rand() % mask + 1 instead of rand() & mask | 1 ?

No. I'm deliberately outputting a random x, with 0 < x < 1 where the inequalities are STRICT. Thus (ruf() * N) will be at most N-1. That would NOT be the case if ruf() were allowed to return 1.0. (Debugging might miss this once-in-a-billion problem.)

I ran your code.Using your ruff() the resulting histogram is a negative exponential. Using a unfirm distribution results in a log normal distribution.

Your ruf() does not appear to be a uniform distribution. I checd my resits in C against Scilab using their random uniform distribution.

Code:
double ruf(void){
    double k1,k2;
    unsigned int mask = RAND_MAX>>2;
    k1 = sqrt((double)((rand() & mask | 1) ));
    k2 = (k1/(double)(mask + 1));
    return k2;
}

Again, where did the sqrt come from? Test with my ACTUAL code please, not with you confused version of it.
 
I am disappointed -- but should not be surprised -- that no one found anything interesting in my code. That's OK, What I do NOT like are the incorrect implications that my code is defective! :)

It's just another of my many perversions, but I've always been a fan of "nifty one-liners." Need to convert a Gregorian date to day of the week? Why use a loop if there's a nifty one-line macro
In webpages you need to do that sometimes so it’s easy to do it in PHP (code from ChatGPT)
Code:
$date = '2023-05-05'; // The date you want to convert
$day_of_week = date('l', strtotime($date)); // 'l' stands for the full name of the day of the week

If someone has already written a function to do XXX, of course one can invoke that function and it will be a one-liner that does XXX. Duh.
But somebody had to write that function! That somebody could be anyone who finds it FUN to write low-level code. It could be (and often was) me. (There's a variety of consumer devices circa 2000 that run code or hardware algorithms written or designed by me.)

I'm reminded of the time I tried to explain the power of Unix by pointing out that the rot13 service could be obtained in Unix with simply
tr n-zN-Za-mA-M a-mA-Mn-zN-Z​
I got a reply like "So what? Microsoft has the same thing: you just download rot13.exe."

Talk about missing the point!

C:
#include        <stdio.h>
#include        <stdlib.h>

#define         NBITS           27 // number of bits returned by random()
#define         MAXRAND         0x7ffffff
#define         NB_TO_M(nb)     (((unsigned long long)1 << (nb)) - 1)

// Do NOT try to understand the following arithmetic gibberish.
// Just know that IT WORKS !!!
#define         M_TO_NB(m)      \
        ((m) / ((m) % 255 + 1) / 255 % 255 * 8 + 7 - 100 / ((m) % 255 + 14))
In books like the Clean Coder they say code should be self-documenting - so you could have helpful function and variable names even if they are more than ten characters long. I'm not sure why you're using an unsigned long long.... it allows up to 18,446,744,073,709,551,615 and might be slower than a smaller integer type.
I did NOT obfuscate the code I delivered to customers, The code I post HERE at IIDB is often deliberately terse to be more challenging. The M_TO_NB macro is seldom if ever used, but seemed like an interesting example for a post about one-liners.

The reason I use long long is in case you apply the macro to such a 64-bit integer. Much code will use such integers, if only in the future. Why limit the utility of the macro?

As for "might be slower", the MAXRAND (or similar) argument provided to the macro will be a compile-time constant, so the invoked macro is a compile-time constant also. It will be computed ZERO times during execution. (Some scenarios will execute the macro ONCE during execution.)

Still don't see how the code in your post has any valuem and as usal you don't seem able to explain why.

A normal distribution can have non zero means. Look at the equation. The normalized variate has zero mean and a stAndard deviation of 1. If yOu do not understnd that then you really do not undertsnd and your polar coodrnates and 2d is just hand waving.

I tried to explain that the function returns a 2-D gaussian in polar coordinates. And that I wasn't trying to complicate needlessly, but rather that it's EASIER to compute the 2D gaussian variates (and in polar coordinates) than to calculate a 1-D variate. (Similarly sometimes integrating a 2D gaussian is easier than integrating a 1D!)
Your typical post. A moving goal post. This is why I don't usually reond to your posts.
Not responding would probably work well.

Making it easier to read.

double ruf(void){
double k1,k2;
unsigned int mask = RAND_MAX>>2;
k1 = sqrt((double)((rand() & mask | 1) ));
k2 = (k1/(double)(mask + 1));
return k2;
}
There's an unrelated sqrt that somehow got interjected into your version of my code.
sqrt((double)((rand() & mask | 1) )) is ambiguous. You have to specify grouping for the logic.

Wrong. C defines precedence, so the "grouping" here is defined. Most coders don't have a problem with (a*b*c + 3*f + d) and because useless parentheses become distracting, that expression is more readable than ((((a*b)*c)+(3*f))+d). Admittedly, most programmers haven't memorized all the precedences, and omitting the parentheses from ((rand() & mask) | 1) can be called obfuscation, Note that in the wrong-precedence version the "| 1" would have no effect. Thus the precedence can be immediately deduced by anyone who's forgotten it.

sqrt((double)(((rand() & mas) | 1) )) or sqrt((double)((rand() & (mask | 1)) ));

Note that the compiler flags a warning ob the ambiguity. Also nesting built in function calls can lead to problems. The compiler parser may not always implement what yiou intend.

"Nesting built in function calls can lead to problems", while perhaps not completely wrong, is confused. Code either does or does not comply with spec. Mine does.

I actually ensure that my code produces no warnings by default (gcc -W). Perhaps you use compiler flags that led to more stringent warnings. My experience is that "-W" flags possible real problems. If you prefer whining about parentheses, that's fine for you.

Did you mean rand() % mask + 1 instead of rand() & mask | 1 ?

No. I'm deliberately outputting a random x, with 0 < x < 1 where the inequalities are STRICT. Thus (ruf() * N) will be at most N-1. That would NOT be the case if ruf() were allowed to return 1.0. (Debugging might miss this once-in-a-billion problem.)

I ran your code.Using your ruff() the resulting histogram is a negative exponential. Using a unfirm distribution results in a log normal distribution.

Your ruf() does not appear to be a uniform distribution. I checd my resits in C against Scilab using their random uniform distribution.

Code:
double ruf(void){
    double k1,k2;
    unsigned int mask = RAND_MAX>>2;
    k1 = sqrt((double)((rand() & mask | 1) ));
    k2 = (k1/(double)(mask + 1));
    return k2;
}

Again, where did the sqrt come from? Test with my ACTUAL code please, not with you confused version of it.
I'm kind of sad you haven't engaged at all with my discussion on using N bit encryption as a generator for addressable random N/2 bit values, so random values can be pre-allocated to an asynchronous process deterministically.

I'm curious if there are better manifolds to work with than AES
 
I am disappointed -- but should not be surprised -- that no one found anything interesting in my code. That's OK, What I do NOT like are the incorrect implications that my code is defective! :)
Well I thought this was interesting:
// Do NOT try to understand the following arithmetic gibberish.
// Just know that IT WORKS !!!

This gives the impression that you're an incredibly bad programmer but maybe you were just being tongue in cheek.
It's just another of my many perversions, but I've always been a fan of "nifty one-liners." Need to convert a Gregorian date to day of the week? Why use a loop if there's a nifty one-line macro
In webpages you need to do that sometimes so it’s easy to do it in PHP (code from ChatGPT)
Code:
$date = '2023-05-05'; // The date you want to convert
$day_of_week = date('l', strtotime($date)); // 'l' stands for the full name of the day of the week
If someone has already written a function to do XXX, of course one can invoke that function and it will be a one-liner that does XXX. Duh.
Well I'm not a fan on one-liners anyway. BTW I think that PHP code is the shortest code that does that in any language. It is built into the language. On the other hand sin() in C is using a math library rather than being built into the language.
But somebody had to write that function!
Same with sin() in C.....
C:
#include        <stdio.h>
#include        <stdlib.h>

#define         NBITS           27 // number of bits returned by random()
#define         MAXRAND         0x7ffffff
#define         NB_TO_M(nb)     (((unsigned long long)1 << (nb)) - 1)

// Do NOT try to understand the following arithmetic gibberish.
// Just know that IT WORKS !!!
#define         M_TO_NB(m)      \
        ((m) / ((m) % 255 + 1) / 255 % 255 * 8 + 7 - 100 / ((m) % 255 + 14))
In books like the Clean Coder they say code should be self-documenting - so you could have helpful function and variable names even if they are more than ten characters long. I'm not sure why you're using an unsigned long long.... it allows up to 18,446,744,073,709,551,615 and might be slower than a smaller integer type.
I did NOT obfuscate the code I delivered to customers, The code I post HERE at IIDB is often deliberately terse to be more challenging.
Well it is annoying to try and understand your code. If you used a lot of well thought out names for variables and methods that would have been good.
The M_TO_NB macro is seldom if ever used, but seemed like an interesting example for a post about one-liners.
In a way it was two lines - but to make it clearer you could have had a lot more brackets and split it onto 3 or 4 "lines"... BTW what does M and NB mean? I assume NB means "number of bits".
 
This recent RNG thing has me thinking about a system I whipped up for making a cryptographic PRNG that allows the RNG to produce deterministic results even for asynchronously executed threads by using an addressing method.

The idea is that you start with a key and 2 64 bit values. You set the first 64 bit value, the "seed", and then generate using the second 64 bit value, the "address", so you can index from zero.

When you get a result, it is guaranteed to be a unique 128 bit value, so to guarantee at least some collisions, you can XOR the top 64 bit integer of the result against the bottom 64 bit integer (I suppose this isn't necessary; you could just pick half, but I wanted their fold...).

This gives the ability to assign RNG interactions as if assigning address space, so the thread running the calculations for an asynchronously launched event can always produce the same result, and there is no contention on the PRNG.

I did see this post, but didn't fully understand it. And I felt I would have nothing useful to add even if I did.

One question: If the random library were defined to be re-entrant, would that be another way to cope with your need? That is, random() and srandom() would each be passed a pointer to a seed structure so that each thread would get deterministic results.

A common C library already provides re-entrant versions of many routines. For example you can call
void *malloc_r(void *reent, size_t nbytes);​
instead of
void *malloc(size_t nbytes);​
when malloc might be interrupted by another thread. Googling now I see that Linux already has just such a random_r() and srandom_r(). (Of course you can always "roll your own.")
 
Not all compilers are the same and parsers have limitations. From experience I found it is best to explicitly specify groupings for logical and algebraic expressions. Portability and reliability.

Order of numerical calculations can result in different numeral ac curacies It is a function of finite digital math.

If you want a random float > 0 and < 1 there are different ways to do it.

You can force bit 0 the least significant bit to always be 1. The lsb is not likely to affect numerical calculations using the random numbers. I bit out of 16 or 32. When converted to a float < 1 the lsb becomes irrelevant.

Or you can skip any zero random numbers.

I always favored directness and simplicity over complexity and cleverness. One can be too clever for one's own good. If coding for actual work I'd go with buf3(); It would be obvious to anyone reading the code.



Testing the code.

Code:
#define MASK (RAND_MAX >> 2)
double RUF(void)
{ return (rand() & MASK | 1) / (double)(MASK+1); }


double ruf2(void){
    unsigned int x = rand();
    if(!(x & 1)) x = x|1;
    return double(x)/double(RAND_MAX+1);
}

 
double ruf3(void){
    unsigned int x;
    while(1){
        if(x = rand()) return(double(x)/double(RAND_MAX+1));
    }
}
int main(){
    srand(unsigned (time(NULL)));
    double x;
    int i,cnt[10],cntz = 0,cnth = 0;;
    for(i = 0;i<10;i++)cnt[i] = 0;
    for(i = 0;i<1000000;i++){

       x = RUF();
       //x = ruf2();
       // x = ruf3();
       if(x >= 1.)cnth += 1;
       if(x == 0.)cntz += 1;
       if(x >  0.0 && x < .1)cnt[0] += 1;
       if(x >= 0.1 && x < .2)cnt[1] += 1;
       if(x >= 0.2 && x < .3)cnt[2] += 1;
       if(x >= 0.3 && x < .4)cnt[3] += 1;
       if(x >= 0.4 && x < .5)cnt[4] += 1;
       if(x >= 0.5 && x < .6)cnt[5] += 1;
       if(x >= 0.6 && x < .7)cnt[6] += 1;
       if(x >= 0.7 && x < .8)cnt[7] += 1;
       if(x >= 0.8 && x < .9)cnt[8] += 1;
       if(x >= 0.9 && x < 1.)cnt[9] += 1;
    }
    printf("= 0  %d  >= 1  %d\n",cntz,cnth);
    for(i = 0;i<10;i++)printf("%d  %d  \n",i,cnt[i]);
return 0;
}
 
This recent RNG thing has me thinking about a system I whipped up for making a cryptographic PRNG that allows the RNG to produce deterministic results even for asynchronously executed threads by using an addressing method.

The idea is that you start with a key and 2 64 bit values. You set the first 64 bit value, the "seed", and then generate using the second 64 bit value, the "address", so you can index from zero.

When you get a result, it is guaranteed to be a unique 128 bit value, so to guarantee at least some collisions, you can XOR the top 64 bit integer of the result against the bottom 64 bit integer (I suppose this isn't necessary; you could just pick half, but I wanted their fold...).

This gives the ability to assign RNG interactions as if assigning address space, so the thread running the calculations for an asynchronously launched event can always produce the same result, and there is no contention on the PRNG.

I did see this post, but didn't fully understand it. And I felt I would have nothing useful to add even if I did.

One question: If the random library were defined to be re-entrant, would that be another way to cope with your need? That is, random() and srandom() would each be passed a pointer to a seed structure so that each thread would get deterministic results.

A common C library already provides re-entrant versions of many routines. For example you can call
void *malloc_r(void *reent, size_t nbytes);​
instead of
void *malloc(size_t nbytes);​
when malloc might be interrupted by another thread. Googling now I see that Linux already has just such a random_r() and srandom_r(). (Of course you can always "roll your own.")
I didn't know the terminology for it. For some reason, I had forgotten "re-entrant"

My consideration started with a concept with the question "how do I construct a game system where cheating is mathematically impossible, and outcomes are deterministic given a series of player decisions?"

I would rather use a system which is known to run fast on many architectures, and which contains a user-controlled provision.

It doesn't contain anything a user can modify. Their history is a record of cryptographic events in a ledger of cryptographic events that anyone can compute and validate.

Player A in World A sent a signed packet to a world to move forward. The world sees that and then responds with a signed acknowledgement of the requested action, and the time at which the result happens. This would have a 64 bit digest which determines the RNG address for the activities.

The result is that the random number generator is accessible on both machines at the same time without having to embed the actual results in the response -- those can be calculated locally for both client and server.

the idea is to break up the responsibility for using an RNG without any trust of any side for any other side.
 
If you like 1 liners more simple.

double ruf2(void){
//returns random numbers > 0 < 1
return double(rand()|1)/double(RAND_MAX+1);
}

For 2^31 iterations no zeroes or >= 1.

Bins > 0 to < 1 in .1 steps. Counts per bin.

214695936
214827008
214695936
214827008
214695936
214695935
214827008
214695936
214827008
214695936

#define MASK (RAND_MAX >> 2)
double RUF(void)
{ return (rand() & MASK | 1) / (double)(MASK+1); }

214958079
214433792
214958080
214433792
214958080
214958080
214433792
214958080
214433792
214958080

It would take a lot of iterations and analysis to do a true comparison of the two functions.
 
Smeting I lrned early on is that software is only as good as the numer of trials used to test it.

So the quetion is more about algoriths than mah [er say.

The Halting Pronlem

Given

Start
input b
input c
a = b + c
output a
End

Can you prove analytically whether once started the code will stop?


In computability theory, the halting problem is the problem of determining, from a description of an arbitrary computer program and an input, whether the program will finish running, or continue to run forever. The halting problem is undecidable, meaning that no general algorithm exists that solves the halting problem for all possible program–input pairs.

You can write code to analyze other code but you end up in he sane pace how do you prove the code that is used to test er code.

So when it comes to compuer securityor reliability he best you can do is run a number of test cases

Obviously there is code you can test by inspection or running all paossible combinations of inputs, so the above is a generalization.
 
In books like the Clean Coder they say code should be self-documenting - so you could have helpful function and variable names even if they are more than ten characters long. I'm not sure why you're using an unsigned long long.... it allows up to 18,446,744,073,709,551,615 and might be slower than a smaller integer type.
Yup. My favorite form of documentation is to split out code into separate well-named functions even if there's no logic benefit from doing so. If it's used only once I figure the compiler is going to inline it anyway but I've found bugs have a hard time hiding when code is sliced small enough and named well enough.
 
Call me childish but I smile when someone clicks Like, and am less happy when someone quotes me without a Like.
I think people ignoring questions (like post #351) is even worse.

Sorry. Do you mean this question?
The M_TO_NB macro is seldom if ever used, but seemed like an interesting example for a post about one-liners.
In a way it was two lines - but to make it clearer you could have had a lot more brackets and split it onto 3 or 4 "lines"... BTW what does M and NB mean? I assume NB means "number of bits".
You're right that NB was "number of bits." And M was "mask." I do pick poor overly-short names. Guilty as charged.
 
Call me childish but I smile when someone clicks Like, and am less happy when someone quotes me without a Like.
I think people ignoring questions (like post #351) is even worse.
Sorry. Do you mean this question?
The M_TO_NB macro is seldom if ever used, but seemed like an interesting example for a post about one-liners.
In a way it was two lines - but to make it clearer you could have had a lot more brackets and split it onto 3 or 4 "lines"... BTW what does M and NB mean? I assume NB means "number of bits".
You're right that NB was "number of bits." And M was "mask." I do pick poor overly-short names. Guilty as charged.
Yes that's the one. BTW I suspect that
((m) / ((m) % 255 + 1) / 255 % 255 * 8 + 7 - 100 / ((m) % 255 + 14))
could be simplified a bit but I'm not sure the precedence of all of the operators (e.g. maybe * is done before +), etc. It really needs lots of brackets - though I think some are unnecessary... like the ones around m.... (unless you had a long expression using M_TO_NB(m))? I wonder how it handles something like a 0xF0F0F etc mask?
 
Back
Top Bottom