1// Copyright 2010 The Go Authors.  All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// gcc '-std=c99' cmplxdivide.c && a.out >cmplxdivide1.go
6
7#include <complex.h>
8#include <math.h>
9#include <stdio.h>
10#include <string.h>
11
12#define nelem(x) (sizeof(x)/sizeof((x)[0]))
13
14double f[] = {
15	0,
16	1,
17	-1,
18	2,
19	NAN,
20	INFINITY,
21	-INFINITY,
22};
23
24char*
25fmt(double g)
26{
27	static char buf[10][30];
28	static int n;
29	char *p;
30
31	p = buf[n++];
32	if(n == 10)
33		n = 0;
34	sprintf(p, "%g", g);
35	if(strcmp(p, "-0") == 0)
36		strcpy(p, "negzero");
37	return p;
38}
39
40int
41iscnan(double complex d)
42{
43	return !isinf(creal(d)) && !isinf(cimag(d)) && (isnan(creal(d)) || isnan(cimag(d)));
44}
45
46double complex zero;	// attempt to hide zero division from gcc
47
48int
49main(void)
50{
51	int i, j, k, l;
52	double complex n, d, q;
53
54	printf("// skip\n");
55	printf("// # generated by cmplxdivide.c\n");
56	printf("\n");
57	printf("package main\n");
58	printf("var tests = []Test{\n");
59	for(i=0; i<nelem(f); i++)
60	for(j=0; j<nelem(f); j++)
61	for(k=0; k<nelem(f); k++)
62	for(l=0; l<nelem(f); l++) {
63		n = f[i] + f[j]*I;
64		d = f[k] + f[l]*I;
65		q = n/d;
66
67		// BUG FIX.
68		// Gcc gets the wrong answer for NaN/0 unless both sides are NaN.
69		// That is, it treats (NaN+NaN*I)/0 = NaN+NaN*I (a complex NaN)
70		// but it then computes (1+NaN*I)/0 = Inf+NaN*I (a complex infinity).
71		// Since both numerators are complex NaNs, it seems that the
72		// results should agree in kind.  Override the gcc computation in this case.
73		if(iscnan(n) && d == 0)
74			q = (NAN+NAN*I) / zero;
75
76		printf("\tTest{complex(%s, %s), complex(%s, %s), complex(%s, %s)},\n",
77			fmt(creal(n)), fmt(cimag(n)),
78			fmt(creal(d)), fmt(cimag(d)),
79			fmt(creal(q)), fmt(cimag(q)));
80	}
81	printf("}\n");
82	return 0;
83}
84