Friday, 29 March 2019

c++ comparison of two double values not working properly




Look at this code:



#include 
#include
using namespace std;
class Sphere
{

double r;
public:
double V() const { return (4/3) * 3.14 * pow(r,3); }
bool equal(const Sphere& s) const
{
cout << V() << " == " << s.V() << " : " << ( V() == s.V() );
return ( V() == s.V() );

}


explicit Sphere(double rr = 1): r(rr){}

};
main()
{
Sphere s(3);
s.equal(s);
}



The output is 84.78 == 84.78 : 0 which means the same method doesn't return the same value every time, even though all parameters are static?



But if I write 3.0 instead of 3.14 in the V() method definition, like this:



double V() const { return (4/3) * 3.0 * pow(r,3); }


Then, the output is: 84.78 == 84.78 : 1



What is going on here? I need this method, for my program, which will compare volumes of two objects, but it is impossible? I banged my head for so long to figure out what is the cause of the problem and luckily I found it, but now I don't understand why?? Does it have something to do with the compiler (GCC) or am I missing something important here?



Answer



Comparing floating point values using the == operator is very error prone; two values that should be equal may not be due to arithmetic rounding errors. The common way to compare these is to use an epsilon:



bool double_equals(double a, double b, double epsilon = 0.001)
{
return std::abs(a - b) < epsilon;
}

Cast one dynamic to the type of another in c#

I'm trying to write a generic function that compares expected results from reflection (but where the expectation is provided in configuration by users rather than at design time) with the actual results for arbitrary properties.



I'm running into an issue where the expected type doesn't always reflect the returned type by default - e.g. my reflection result (in a dynamic) may be an int, where the expected result is an enum member (inheriting from int).



I'd like, therefore to do the following:



if ((dCurrentValue as typeof(this.CheckValue)) != this.CheckValue) { oOut = false; }



however, this doesn't seem to work. From fumbling around the web, I've managed to find that either System.Activator or Convert.ChangeType() may be my friends. However, so far they're not working as I'd expect - e.g.:



dCurrentValue = Convert.ChangeType(dCurrentValue, this.CheckValue.GetType());


throws an exception (for the pair that alerted me to the issue) that Invalid cast from 'System.Int32' to 'Microsoft.Office.Core.MsoTriState' - which I know to be wrong, since:



(int)Microsoft.Office.Core.MsoTriState.msoTrue == -1                                    // true
((Microsoft.Office.Core.MsoTriState)(-1)) == Microsoft.Office.Core.MsoTriState.msoTrue // true



NB that whilst I could put a shim in to solve for MsoTriState (i.e. check type of this.CheckValue, and explicit cast if applicable), I'd rather do this in a way that'll work for unknown enum entries.



EDIT: Thanks to the comments below, I've added a test before my tests of the form:



if (((Type) this.CheckValue.GetType()).IsEnum)
{
dCurrentValue = Enum.Parse(this.CheckValue.GetType(), dCurrentValue.ToString());
}



which fixes my immediate issue. My guess is this combined with Convert.ChangeType() (which as I've mentioned, doesn't seem to like converting Enums to Ints) will cover most situations.

c++ - double or float comparison

I've seen posts like:



What is the most effective way for float and double comparison?



Compare two floats



And many other related posts.



I saw in d3js library, it uses the following comparison:




  return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;


Is it OK to use this in C/C++ to do the comparison of double and float?

error handling - PHP - failed to open stream: no such host is known



Hi i have a issue in simple html dom code it show this error :-




file_get_contents(http://www.arakne-links.com)
[function.file-get-contents]: failed to open stream:

php_network_getaddresses: getaddrinfo failed: No such host is known.
in D:\xampp\htdocs\scrap\simple_html_dom.php on line 75




because this url http://www.arakne-links.c is not working now i want



to know is there any way to skip the url which is not working..



here is the code which i am using




ini_set('display_errors', 'on'); 
include_once('../../simple_html_dom.php');

// create HTML DOM

$htmls = file_get_html('http://info.vilesilencer.com/top');
foreach($htmls->find('a[rel="nofollow"]') as $e):
$test = $e->href;
$url = array( $test );
$html = array();

foreach( $url as $key=>$value ) {

// get html plain-text for webpage & assign to html array.

$html = file_get_html( trim($value) );

// echo html plain text:
echo $html->find('title', 0)->innertext;

}

endforeach;


Please Help me to fix this issue.



Thankyou


Answer



How about checking the URL before parsing?



ini_set('display_errors', 'on'); 

include_once('simple_html_dom.php');

function urlOk($url) {
$headers = @get_headers($url);
if($headers[0] == 'HTTP/1.1 200 OK') return true;
else return false;
}

// create HTML DOM


$htmls = file_get_html('http://info.vilesilencer.com/top');
foreach($htmls->find('a[rel="nofollow"]') as $e):
$test = $e->href;
$url = array( $test );
$html = array();
foreach( $url as $key=>$value ) {
// get html plain-text for webpage & assign to html array.
if (urlOk(trim($value))) {
$html = file_get_html( trim($value) );
echo $html->find('title', 0)->innertext;

echo "
";
} else {
echo 'Error: URL '.$value.' doesn\'t exist.
';
}
}
endforeach;
?>

sql - MySQL Merging multiple rows with the same ID into one row




I have a table with rows which have multiple of the same IDs I want to figure out an SQL query which allow me to but the relevant field number and value into a separate column for example; for value 1.3 a new column would be created called first, 1.6 would be last name and so on. I want to attempt to get all of the information into one row so for each where the lead_id value is 79 there would be only one row instead of 9 rows. I'm not sure if this would be at all possible? I have put a preview of the database structure below in an attempt to show what I mean.




ID   lead_id   field_number   Value

1 79 1.3 John
2 79 1.6 Doe
3 79 2 johndoe@example.com
4 79 6 POSTCODE
5 79 3 01332 1234567
6 79 4 DATE OF BIRTH
7 79 7 APPLICATION ID

8 79 9 CITY NAME
9 79 5 RESUME URL
10 80 1.3 Jane
11 80 1.6 Doe
12 80 2 janedoe@example.com
13 80 6 POSTCODE
14 80 3 01332 1234567
15 80 4 DATE OF BIRTH
16 80 7 APPLICATION ID
17 80 9 CITY NAME

18 80 5 RESUME URL


Any help would be greatly appreciated!


Answer



You can use multiple SELECT queries for this, e.g.:



SELECT t.lead_id,
(SELECT value FROM table WHERE lead_id = t.lead_id AND field_number = 1.3) as 'first name',
(SELECT value FROM table WHERE lead_id = t.lead_id AND field_number = 1.6) as 'last name',

(SELECT value FROM table WHERE lead_id = t.lead_id AND field_number = 2) as 'email',
(SELECT value FROM table WHERE lead_id = t.lead_id AND field_number = 6) as 'post code',
(SELECT value FROM table WHERE lead_id = t.lead_id AND field_number = 3) as 'phone',
(SELECT value FROM table WHERE lead_id = t.lead_id AND field_number = 4) as 'dob'
FROM table t


You can add more SELECTs for more columns.


c++ - Why are elementwise additions much faster in separate loops than in a combined loop?



Suppose a1, b1, c1, and d1 point to heap memory and my numerical code has the following core loop.



const int n = 100000;

for (int j = 0; j < n; j++) {
a1[j] += b1[j];
c1[j] += d1[j];

}


This loop is executed 10,000 times via another outer for loop. To speed it up, I changed the code to:



for (int j = 0; j < n; j++) {
a1[j] += b1[j];
}

for (int j = 0; j < n; j++) {

c1[j] += d1[j];
}


Compiled on MS Visual C++ 10.0 with full optimization and SSE2 enabled for 32-bit on a Intel Core 2 Duo (x64), the first example takes 5.5 seconds and the double-loop example takes only 1.9 seconds. My question is: (Please refer to the my rephrased question at the bottom)



PS: I am not sure, if this helps:



Disassembly for the first loop basically looks like this (this block is repeated about five times in the full program):




movsd       xmm0,mmword ptr [edx+18h]
addsd xmm0,mmword ptr [ecx+20h]
movsd mmword ptr [ecx+20h],xmm0
movsd xmm0,mmword ptr [esi+10h]
addsd xmm0,mmword ptr [eax+30h]
movsd mmword ptr [eax+30h],xmm0
movsd xmm0,mmword ptr [edx+20h]
addsd xmm0,mmword ptr [ecx+28h]
movsd mmword ptr [ecx+28h],xmm0
movsd xmm0,mmword ptr [esi+18h]

addsd xmm0,mmword ptr [eax+38h]


Each loop of the double loop example produces this code (the following block is repeated about three times):



addsd       xmm0,mmword ptr [eax+28h]
movsd mmword ptr [eax+28h],xmm0
movsd xmm0,mmword ptr [ecx+20h]
addsd xmm0,mmword ptr [eax+30h]
movsd mmword ptr [eax+30h],xmm0

movsd xmm0,mmword ptr [ecx+28h]
addsd xmm0,mmword ptr [eax+38h]
movsd mmword ptr [eax+38h],xmm0
movsd xmm0,mmword ptr [ecx+30h]
addsd xmm0,mmword ptr [eax+40h]
movsd mmword ptr [eax+40h],xmm0


The question turned out to be of no relevance, as the behavior severely depends on the sizes of the arrays (n) and the CPU cache. So if there is further interest, I rephrase the question:




Could you provide some solid insight into the details that lead to the different cache behaviors as illustrated by the five regions on the following graph?



It might also be interesting to point out the differences between CPU/cache architectures, by providing a similar graph for these CPUs.



PPS: Here is the full code. It uses TBB Tick_Count for higher resolution timing, which can be disabled by not defining the TBB_TIMING Macro:



#include 
#include
#include
#include


//#define TBB_TIMING

#ifdef TBB_TIMING
#include
using tbb::tick_count;
#else
#include
#endif


using namespace std;

//#define preallocate_memory new_cont

enum { new_cont, new_sep };

double *a1, *b1, *c1, *d1;


void allo(int cont, int n)

{
switch(cont) {
case new_cont:
a1 = new double[n*4];
b1 = a1 + n;
c1 = b1 + n;
d1 = c1 + n;
break;
case new_sep:
a1 = new double[n];

b1 = new double[n];
c1 = new double[n];
d1 = new double[n];
break;
}

for (int i = 0; i < n; i++) {
a1[i] = 1.0;
d1[i] = 1.0;
c1[i] = 1.0;

b1[i] = 1.0;
}
}

void ff(int cont)
{
switch(cont){
case new_sep:
delete[] b1;
delete[] c1;

delete[] d1;
case new_cont:
delete[] a1;
}
}

double plain(int n, int m, int cont, int loops)
{
#ifndef preallocate_memory
allo(cont,n);

#endif

#ifdef TBB_TIMING
tick_count t0 = tick_count::now();
#else
clock_t start = clock();
#endif

if (loops == 1) {
for (int i = 0; i < m; i++) {

for (int j = 0; j < n; j++){
a1[j] += b1[j];
c1[j] += d1[j];
}
}
} else {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
a1[j] += b1[j];
}

for (int j = 0; j < n; j++) {
c1[j] += d1[j];
}
}
}
double ret;

#ifdef TBB_TIMING
tick_count t1 = tick_count::now();
ret = 2.0*double(n)*double(m)/(t1-t0).seconds();

#else
clock_t end = clock();
ret = 2.0*double(n)*double(m)/(double)(end - start) *double(CLOCKS_PER_SEC);
#endif

#ifndef preallocate_memory
ff(cont);
#endif

return ret;

}


void main()
{
freopen("C:\\test.csv", "w", stdout);

char *s = " ";

string na[2] ={"new_cont", "new_sep"};


cout << "n";

for (int j = 0; j < 2; j++)
for (int i = 1; i <= 2; i++)
#ifdef preallocate_memory
cout << s << i << "_loops_" << na[preallocate_memory];
#else
cout << s << i << "_loops_" << na[j];
#endif


cout << endl;

long long nmax = 1000000;

#ifdef preallocate_memory
allo(preallocate_memory, nmax);
#endif

for (long long n = 1L; n < nmax; n = max(n+1, long long(n*1.2)))

{
const long long m = 10000000/n;
cout << n;

for (int j = 0; j < 2; j++)
for (int i = 1; i <= 2; i++)
cout << s << plain(n, m, j, i);
cout << endl;
}
}



(It shows FLOP/s for different values of n.)



enter image description here


Answer



Upon further analysis of this, I believe this is (at least partially) caused by data alignment of the four pointers. This will cause some level of cache bank/way conflicts.



If I've guessed correctly on how you are allocating your arrays, they are likely to be aligned to the page line.




This means that all your accesses in each loop will fall on the same cache way. However, Intel processors have had 8-way L1 cache associativity for a while. But in reality, the performance isn't completely uniform. Accessing 4-ways is still slower than say 2-ways.



EDIT : It does in fact look like you are allocating all the arrays separately.
Usually when such large allocations are requested, the allocator will request fresh pages from the OS. Therefore, there is a high chance that large allocations will appear at the same offset from a page-boundary.



Here's the test code:



int main(){
const int n = 100000;


#ifdef ALLOCATE_SEPERATE
double *a1 = (double*)malloc(n * sizeof(double));
double *b1 = (double*)malloc(n * sizeof(double));
double *c1 = (double*)malloc(n * sizeof(double));
double *d1 = (double*)malloc(n * sizeof(double));
#else
double *a1 = (double*)malloc(n * sizeof(double) * 4);
double *b1 = a1 + n;
double *c1 = b1 + n;
double *d1 = c1 + n;

#endif

// Zero the data to prevent any chance of denormals.
memset(a1,0,n * sizeof(double));
memset(b1,0,n * sizeof(double));
memset(c1,0,n * sizeof(double));
memset(d1,0,n * sizeof(double));

// Print the addresses
cout << a1 << endl;

cout << b1 << endl;
cout << c1 << endl;
cout << d1 << endl;

clock_t start = clock();

int c = 0;
while (c++ < 10000){

#if ONE_LOOP

for(int j=0;j a1[j] += b1[j];
c1[j] += d1[j];
}
#else
for(int j=0;j a1[j] += b1[j];
}
for(int j=0;j c1[j] += d1[j];

}
#endif

}

clock_t end = clock();
cout << "seconds = " << (double)(end - start) / CLOCKS_PER_SEC << endl;

system("pause");
return 0;

}





Benchmark Results:





2 x Intel Xeon X5482 Harpertown @ 3.2 GHz:




#define ALLOCATE_SEPERATE
#define ONE_LOOP
00600020
006D0020
007A0020
00870020
seconds = 6.206

#define ALLOCATE_SEPERATE

//#define ONE_LOOP
005E0020
006B0020
00780020
00850020
seconds = 2.116

//#define ALLOCATE_SEPERATE
#define ONE_LOOP
00570020

00633520
006F6A20
007B9F20
seconds = 1.894

//#define ALLOCATE_SEPERATE
//#define ONE_LOOP
008C0020
00983520
00A46A20

00B09F20
seconds = 1.993


Observations:




  • 6.206 seconds with one loop and 2.116 seconds with two loops. This reproduces the OP's results exactly.


  • In the first two tests, the arrays are allocated separately. You'll notice that they all have the same alignment relative to the page.


  • In the second two tests, the arrays are packed together to break that alignment. Here you'll notice both loops are faster. Furthermore, the second (double) loop is now the slower one as you would normally expect.





As @Stephen Cannon points out in the comments, there is very likely possibility that this alignment causes false aliasing in the load/store units or the cache. I Googled around for this and found that Intel actually has a hardware counter for partial address aliasing stalls:



http://software.intel.com/sites/products/documentation/doclib/stdxe/2013/~amplifierxe/pmw_dp/events/partial_address_alias.html









Region 1:



This one is easy. The dataset is so small that the performance is dominated by overhead like looping and branching.



Region 2:



Here, as the data sizes increases, the amount of relative overhead goes down and the performance "saturates". Here two loops is slower because it has twice as much loop and branching overhead.



I'm not sure exactly what's going on here... Alignment could still play an effect as Agner Fog mentions cache bank conflicts. (That link is about Sandy Bridge, but the idea should still be applicable to Core 2.)




Region 3:



At this point, the data no longer fits in L1 cache. So performance is capped by the L1 <-> L2 cache bandwidth.



Region 4:



The performance drop in the single-loop is what we are observing. And as mentioned, this is due to the alignment which (most likely) causes false aliasing stalls in the processor load/store units.



However, in order for false aliasing to occur, there must be a large enough stride between the datasets. This is why you don't see this in region 3.




Region 5:



At this point, nothing fits in cache. So you're bound by memory bandwidth.






2 x Intel X5482 Harpertown @ 3.2 GHz
Intel Core i7 870 @ 2.8 GHz
Intel Core i7 2600K @ 4.4 GHz


garbage collection - Is there a destructor for Java?



Is there a destructor for Java? I don't seem to be able to find any documentation on this. If there isn't, how can I achieve the same effect?



To make my question more specific, I am writing an application that deals with data and the specification say that there should be a 'reset' button that brings the application back to its original just launched state. However, all data have to be 'live' unless the application is closed or reset button is pressed.



Being usually a C/C++ programmer, I thought this would be trivial to implement. (And hence I planned to implement it last.) I structured my program such that all the 'reset-able' objects would be in the same class so that I can just destroy all 'live' objects when a reset button is pressed.



I was thinking if all I did was just to dereference the data and wait for the garbage collector to collect them, wouldn't there be a memory leak if my user repeatedly entered data and pressed the reset button? I was also thinking since Java is quite mature as a language, there should be a way to prevent this from happening or gracefully tackle this.


Answer




Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor.



There is an inherited method called finalize, but this is called entirely at the discretion of the garbage collector. So for classes that need to explicitly tidy up, the convention is to define a close method and use finalize only for sanity checking (i.e. if close has not been called do it now and log an error).



There was a question that spawned in-depth discussion of finalize recently, so that should provide more depth if required...


php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...