Differing output between C++ and NativeCall in Raku - c++

I am trying to write a function for cumulative distribution function taken from here.
This is my cpp code:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double normalCDF( double x )
{
return 0.5 * ( 1.0 + erf( M_SQRT1_2 * x ) );
}
int main() {
cout << normalCDF(4.8) << endl;
cout << normalCDF(5.4) << endl;
cout << normalCDF(5.6) << endl;
cout << normalCDF(5.8) << endl;
cout << normalCDF(5.1) << endl;
cout << normalCDF(-37.5) << endl;
cout << normalCDF(-36.0) << endl;
cout << normalCDF(-37.6) << endl;
cout << normalCDF(-37.5) << endl;
return 0;
}
This is the output when compiled in linux with gcc 6.3.0
0.999999
1
1
1
1
0
0
0
0
I wanted to call same code from raku using NativeCall, so I modified code
test.cpp
extern "C" double normalCDF( double x )
{
return 0.5 * ( 1.0 + erf( M_SQRT1_2 * x ) );
}
created dynamic shared .so library and wrote nativecall code as:
use NativeCall;
sub normalCDF(num64) returns num64 is native('libtest.so') { * };
say normalCDF((4.8).Num);
say normalCDF((5.4).Num);
say normalCDF((5.6).Num);
say normalCDF((5.8).Num);
say normalCDF((5.1).Num);
say normalCDF((-37.5).Num);
say normalCDF((-36.0).Num);
say normalCDF((-37.6).Num);
say normalCDF((-37.5).Num);
The output is:
0.999999206671848
0.9999999666795515
0.9999999892824097
0.9999999966842541
0.9999998301732593
0
0
0
0
Why is the output of same algorithm differing, though the data containers are used as recommended.
System information:
Ubuntu 18.04 64bit with gcc 6.3.0
Rakudo is 2019.07.1 version.

You need to print the floating point numbers with increased precision. The following will give you the maximum precision:
#include <limits>
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double normalCDF( double x )
{
return 0.5 * ( 1.0 + erf( M_SQRT1_2 * x ) );
}
int main() {
typedef std::numeric_limits< double > dmax;
cout.precision(dmax::max_digits10);
cout << normalCDF(4.8) << endl;
cout << normalCDF(5.4) << endl;
cout << normalCDF(5.6) << endl;
cout << normalCDF(5.8) << endl;
cout << normalCDF(5.1) << endl;
cout << normalCDF(-37.5) << endl;
cout << normalCDF(-36.0) << endl;
cout << normalCDF(-37.6) << endl;
cout << normalCDF(-37.5) << endl;
return 0;
}
Notice the #include <limits> and the first two lines in main, although line 2 is what matters.

Related

GCD recursion function RTE in some IDEs

Trying to implement gcd int function using Euclidean Algorithm with recursion. Results from CodeBlocks differ from IDEone (which I use to test my code before submitting to a CP website, TLX: https://tlx.toki.id, which I assume has similar compilers etc. because a lot of times IDEone and TLX got RTE while in CodeBlocks it ran without any problem). First Question: 1. Do they actually have something different that affects the output?
My first attempt was as follows:
#include <iostream>
#include <cmath>
using namespace std;
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stdio.h>
#define pass (void)0
#include <cstdio>
#include <cstring>
#define ll long long
int gcd(int x, int y){
if(y!=0){
gcd(y, x%y);
//return x%y;
} else {
return x;
}
}
int main() {
cout << "test" << endl;
int z = gcd(100, 10);
cout << z << " bruh" << endl;
cout << "hello" << endl;
}
which IDEone spits out
Runtime error #stdin #stdout 0.01s 5380KB
test
while it ran as expected (z = 1 and prints out the correct stuff) in CodeBlocks
I tried to pinpoint where the error exactly occurs by 1. printing out at what part of the code my computer went error by the following way
void gcd(int x, int y){
if(y!=0){
cout << "if " << x << ", " << y << endl;
gcd(y, x%y);
} else {
cout << "else " << x << ", " << y << endl;
//return x;
}
}
int main() {
cout << "test" << endl;
//int z = gcd(100, 10);
gcd(100, 10);
//cout << z << " bruh" << endl;
cout << "hello" << endl;
}
which in both IDE, it outputted:
test
if 100, 10
else 10, 0
hello
then I also tried:
int gcd(int x, int y){
if(y!=0){
gcd(y, x%y);
//return x%y;
} else {
return x;
}
}
int main() {
cout << "test" << endl;
int z = gcd(100, 10);
cout << z << " bruh" << endl;
cout << "hello" << endl;
}
CodeBlocks outputted the first, while IDEone had an error as in the second
test
10 bruh
hello
Runtime error #stdin #stdout 0.01s 5380KB
test
from what I've tried and understand so far, it seems there's an error when the function gcd() calls the gcd() function. 2. Is my assumption correct? 3. and how am I supposed to solve this problem?
Thanks in advance
The problem is that the recursive case of the gcd() function does not run a return statement. Thus, it should be modified like this:
int gcd(int x, int y){
if(y!=0){
return gcd(y, x%y);
} else {
return x;
}
}
This could easily have been caught by enabling and reading compiler warnings.

Test an integer value to determine if it is odd or even in C++

I have to write a program to test an integer value to determine if it is odd or even, and make sure my output is clear and complete. In other words, I have to write the output like "the value 4 is an even integer". I was also hinted that I have to check the value using the remainder modulo.
The issue I have is with the scanf() function. I get a syntax error:
'%=' expected a ')'
How do I fix this?
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
int main()
{
int number = 0;
cout << "enter an integer ";
int scanf(%=2 , &number);
if (number == 0)
cout << "the value" << number << "is even";
else
cout << "the value" << number << "is odd";
return 0;
}
You are using scanf() incorrectly (read the scanf() documentation on cppreference.com). The first parameter expects a null-terminated string containing the format to scan, but you are not passing in anything that even resembles a string. What you are passing in is not valid string syntax, per the C++ language standard. That is why you are getting a syntax error.
You need to change this line:
int scanf(%=2 , &number);
To this instead:
scanf("%d", &number);
Though, in C++ you really should be using std::cin instead for input (you are already using std::cout for output):
std::cin >> number;
Try this:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
int number = 0;
cout << "enter an integer ";
if (cin >> number)
{
if ((number % 2) == 0)
cout << "the value " << number << " is even";
else
cout << "the value " << number << " is odd";
}
else
cout << "the value is invalid";
return 0;
}
I know this question is a little dated, however, if you are able to use modern C++ features. You can write a constexpr helper function such as this:
#include <cstdint>
constexpr bool isEven(uint32_t value) {
return ((value%2) == 0);
}
Then in your main function, you can traverse through a loop of N integers and output your display such as:
#include <iostream>
#include <iomanip>
int main() {
for ( int i = 0; i < 100; i++ ) {
std::cout << std::setw(3) << std::setfill('0') << i << " is "
<< (isEven(i) ? "even" : "odd") << '\n';
}
return 0;
}
It's literally that simple. Here's another nice feature of using the constexpr helper function... You can also format your output as such:
int main() {
for ( int i = 0; i < 100; i++ ) {
std::cout << std::setw(3) << std::setfill('0') << i << ": "
<< std::boolalpha << isEven(i) << '\n';
}
return true;
}
If you are looking for something that is more efficient than using the modulo operator you can bitwise & with the least significant digit... The code above would then become:
#include <cstdint>
constexpr bool isOdd(uint32_t value) {
return (value&1);
}
And using it would be very similar as above, just make sure you reverse the wording in your output to match that from the function being used...
#include <iostream>
#include <iomanip>
int main() {
for ( int i = 0; i < 100; i++ ) {
std::cout << std::setw(3) << std::setfill('0') << i << " is "
<< (isOdd(i) ? "odd" : "even") << '\n';
}
return 0;
}
Again you can use the std::boolalpha manipulator to get this kind of output:
int main() {
for ( int i = 0; i < 100; i++ ) {
std::cout << std::setw(3) << std::setfill('0') << i << ": "
<< std::boolalpha << isOdd(i) << '\n';
}
return true;
}

C++ vector confusion with .size() result

With the code below, I cannot figure out why numbs[numbs.size()] doesn't give me an appropriate response. I would assume it would give me the last item in the sorted vector, in this case it should be the largest. Yet, cout << numbs[numbs.size()]spits out garbage, e.g.
Number 1 entered. [1], smallest: 1. there are 1 elements in the vector. 1.36617e-231 is the largest.
#include <iostream>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <algorithm>
using namespace std;
int main()
{
double number_input = 0.0;
string unit = " ";
vector<double> numbs;
while (cin >> number_input)
{
numbs.push_back(number_input);
cout << "Number " << number_input << "entered.\n";
for(int i = 0; i < numbs.size(); ++i)
{
cout << "[" << numbs[i] << "],";
}
sort(numbs.begin(),numbs.end());
cout << "smallest: " << numbs[0] << endl;
cout << "there are " << numbs.size() << " elements in the vector.\n";
cout << numbs[numbs.size()] << " is the largest.";
}
return 0;
}
Indexes in a vector are 0-based, just as arrays are. So the last value in a vector v is v[ v.size() - 1 ] assuming v.size() > 0

Is assigning a value while using it valid c++?

I had a boolean that needs to be flipped each time its used, since the code was rather simple every other line was me flipping the boolean. I fiddled around a little and came up with this (even more simplified example)
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
bool flippy = 0;
cout << (flippy = !flippy) << "\n";
cout << (flippy = !flippy) << "\n";
cout << (flippy = !flippy) << "\n";
cout << (flippy = !flippy) << "\n";
system("PAUSE");
return 0;
}
It produces 1 0 1 0 as expected but looks a bit odd, is this valid use of the language?
Yes it is valid.
It is not exactlly something I would call good style.
Your code is of course valid. You can also use a bitset as the following example.
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
bitset<1> myBit;
cout << myBit << endl;
cout << myBit.flip() << endl;
cout << myBit.flip() << endl;
cout << myBit.flip() << endl;
}

Rounding to nearest number in C++ using Boost?

Is there a way to round to the nearest number in the Boost library? I mean any number, 2's, 5's, 17's and so on and so forth.
Or is there another way to do it?
You can use lround available in C99.
#include <cmath>
#include <iostream>
int main() {
cout << lround(1.4) << "\n";
cout << lround(1.5) << "\n";
cout << lround(1.6) << "\n";
}
(outputs 1, 2, 2).
Check your compiler documentation if and/or how you need to enable C99 support.
Boost Rounding Functions
For example:
#include <boost/math/special_functions/round.hpp>
#include <iostream>
#include <ostream>
using namespace std;
int main()
{
using boost::math::lround;
cout << lround(0.0) << endl;
cout << lround(0.4) << endl;
cout << lround(0.5) << endl;
cout << lround(0.6) << endl;
cout << lround(-0.4) << endl;
cout << lround(-0.5) << endl;
cout << lround(-0.6) << endl;
}
Output is:
0
0
1
1
0
-1
-1
int nearest = 5;
int result = (input+nearest/2)/nearest*nearest;
You actually don't need Boost at all, just the C library included in the C++ library. Specifically, you need to include the cmath header:
Round up a number: ceil(): http://www.cplusplus.com/reference/clibrary/cmath/ceil/
Round down a number: floor(): http://www.cplusplus.com/reference/clibrary/cmath/floor/
You can write your own round function then:
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <utility>
double roundFloat(double x)
{
double base = floor( x );
if ( x > ( base + 0.5 ) )
return ceil( x );
else return base;
}
int main()
{
std::string strInput;
double input;
printf( "Type a number: " );
std::getline( std::cin, strInput );
input = std::atof( strInput.c_str() );
printf( "\nRounded value is: %7.2f\n", roundFloat( input ) );
return EXIT_SUCCESS;
}