[noob]how to create two functions where second one doing the calculation? - codeblocks

i wrote the following code.
its basically enter 5 variables(a, b, c, f_a, f_b)
and calculate f_c= f_a + (f_b-f_a)*(c-a)/(b-a)
in the main function, i declared and scan all variables,
then i calculate the X, which is equal to f_c.
The question is how can i move the calculation of X to second function calculateFreezingTemp.
I tried to create a function f_c with 5 variables, failed.
double calculateFreezingTemp(double);
int main(void)
{double a, f_a, b, f_b, c, f_c, x;
printf("Please enter the data point A\n");
scanf("%lf %lf", &a, &f_a);
printf("Please enter the data point B\n");
scanf("%lf %lf", &b, &f_b);
printf("Please enter the salinity value between %f and %f\n", a, b);
scanf("%lf", &c);
x = f_a + ((c-a)/(b-a))*(f_b-f_a);
f_c = calculateFreezingTemp(x);
printf("For salinity %f ppt, Freezing Temperature is: %f\t",c, f_c);}
double calculateFreezingTemp(double x)
{double f_c;
f_c=x;
return(f_c);
}

You can pass the input variables to the 'calculateFreezingTemp' function:
f_c = calculateFreezingTemp(a, b, c, f_a, f_b)
and move the calculation into the function:
double calculateFreezingTemp(double a, double b, double c, double f_a, double f_b)
{
return f_a + (f_b-f_a)*(c-a)/(b-a);
}

Related

I want to know why the results are different in these two ways

func main() {
var a int = 10
var b int = 20
swap(&a,&b)
fmt.Println(a,b)
var c int = 10
var d int = 20
swap2(&c,&d)
fmt.Println(c,d)
}
func swap(x, y *int) {
*x = *y
*y = *x
}
func swap2(x, y *int) {
*x,*y= *y,*x
}
//I want to know why the results are different in these two ways
//20 20
//20 10
The reason why swap2(&c,&d) results in different values being set to c and d is because this function consists of a single assignment statement while swap(&a,&b) consists of two assignment statements. Assignment statements have a particular evaluation order in go. From the language specifications:
The assignment proceeds in two phases. First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order. Second, the assignments are carried out in left-to-right order.
With this in mind, let's annotate swap(x, y *int):
// x points to an int with value 10,
// y points to an int with value 20.
*x = *y // 1.
*y = *x // 2.
The first assignment statement occurs first, so do that:
// x points to an int with value 10,
// y points to an int with value 20.
*x = *y // 1. (value of int pointed to by x) = (value of int pointed to by y)
// Now x points to an int with value 20.
*y = *x // 2.
After the first assignment statement finishes, the second assignment statement is run:
// x points to an int with value 10,
// y points to an int with value 20.
*x = *y // 1. (value of int pointed to by x) = (value of int pointed to by y)
// Now x points to an int with value 20.
*y = *x // 2. (value of int pointed to by y) = (value of int pointed to by x)
// Now y points to an int with value 20.
However, because swap2 uses only a single assignment statement, we have to be careful about what happens in what order. The specifications say that the pointer indirections on the left and the expressions on the right are evaluated at the same time:
// x points to an int with value 10
// y points to an int with value 20
*x,*y = *y,*x
// 1. (value of int pointed to by x), (value of int pointed to by y) = 20, 10
Second, the assignments are carried out in left-to-right order. But because we have already evaluated the right-hand side of the statement, those are just values.
// x points to an int with value 10
// y points to an int with value 20
*x,*y = *y,*x
// 1. (value of int pointed to by x), (value of int pointed to by y) = 20, 10
// 2. Now x points to an int with value 20, y points to an int with value 10
Put another way, swap2 does the same thing as this function:
swap3(x, y *int) {
valueX := *x
valueY := *y
*x = valueY
*y = valueX
}
The advantage of the form of swap2 is that the function does not explicitly allocate unnecessary temporary variables.

Creating a parallel arithmetic operator in an infinite loop in C compiler on Mac Terminal

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
void main (void)
{
while(1) // infinite loop
{
int a, b;
printf("Give me an integer a: ");
scanf("%d",&a);
printf("Give me an integer b: ");
scanf("%d",&b);
sum = &a + &b;
product = &a * &b;
difference = &a - &b;
echo Here is your sum, product, and difference:
printf("Sum: %d + d% = %d.\n", a, b, sum);
printf("Product: %d * d% = %d.\n", a, b, product);
printf("Difference: %d - d% = %d.\n", a, b, difference);
return 0;
}
}
I keep getting a syntax error with my void main (void) on line 6
Using child processes to create 3 parallel processes.
This program has a bunch of problems, and it's not doing anything in parallel:
void main (void)
This will usually compile, but according to the C standard it's not correct. The signature of main() that takes no arguments should be int main(void).
sum = &a + &b;
product = &a * &b;
difference = &a - &b;
You're using the addresses of a and b instead of the values, so you'd always get the same results for sum, product, and difference (except that didn't define the last three.) The correct version should be:
sum = a + b;
product = a * b;
difference = a - b;
echo Here is your sum, product, and difference:
This isn't a C construct, so the compiler will complain about this. Use printf().
return 0;
Although you've indicated that the loop should be infinite, it won't be because you exit the function at the end of the loop.

How can I check wether a point is inside the circumcircle of 3 points?

Is there any easy solution? Or has anybody an example of an implementation?
Thanks, Jonas
Lets call
a, b, c our three points,
C the circumcircle of (a, b, c)
and d an other point.
A fast way to determine if d is in C is to compute this determinant:
| ax-dx, ay-dy, (ax-dx)² + (ay-dy)² |
det = | bx-dx, by-dy, (bx-dx)² + (by-dy)² |
| cx-dx, cy-dy, (cx-dx)² + (cy-dy)² |
if a, b, c are in counter clockwise order then:
if det equal 0 then d is on C
if det > 0 then d is inside C
if det < 0 then d is outside C
here is a javascript function that does just that:
function inCircle (ax, ay, bx, by, cx, cy, dx, dy) {
let ax_ = ax-dx;
let ay_ = ay-dy;
let bx_ = bx-dx;
let by_ = by-dy;
let cx_ = cx-dx;
let cy_ = cy-dy;
return (
(ax_*ax_ + ay_*ay_) * (bx_*cy_-cx_*by_) -
(bx_*bx_ + by_*by_) * (ax_*cy_-cx_*ay_) +
(cx_*cx_ + cy_*cy_) * (ax_*by_-bx_*ay_)
) > 0;
}
You might also need to check if your points are in counter clockwise order:
function ccw (ax, ay, bx, by, cx, cy) {
return (bx - ax)*(cy - ay)-(cx - ax)*(by - ay) > 0;
}
I didn't place the ccw check inside the inCircle function because you shouldn't check it every time.
This process doesn't take any divisions or square root operation.
You can see the code in action there: https://titouant.github.io/testTriangle/
And the source there: https://github.com/TitouanT/testTriangle
(In case you are interested in a non-obvious/"crazy" kind of solution.)
One equivalent property of Delaunay triangulation is as follows: if you build a circumcircle of any triangle in the triangulation, it is guaranteed not to contain any other vertices of the triangulation.
Another equivalent property of Delaunay triangulation is: it maximizes the minimal triangle angle (i.e. maximizes it among all triangulations on the same set of points).
This suggests an algorithm for your test:
Consider triangle ABC built on the original 3 points.
If the test point P lies inside the triangle it is definitely inside the circle
If the test point P belongs to one of the "corner" regions (see the shaded regions in the picture below), it is definitely outside the circle
Otherwise (let's say P lies in region 1) consider two triangulations of quadrilateral ABCP: the original one contains the original triangle (red diagonal), and the alternate one with "flipped" diagonal (blue diagonal)
Determine which one if this triangulations is a Delaunay triangulation by testing the "flip" condition, e.g. by comparing α = min(∠1,∠4,∠5,∠8) vs. β = min(∠2,∠3,∠6,∠7).
If the original triangulation is a Delaunay triangulation (α > β), P lies outside the circle. If the alternate triangulation is a Delaunay triangulation (α < β), P lies inside the circle.
Done.
(Revisiting this answer after a while.)
This solution might not be as "crazy" as it might appear at the first sight. Note that in order to compare angles at steps 5 and 6 there's no need to calculate the actual angle values. It is sufficient to know their cosines (i.e. there's no need to involve trigonometric functions).
A C++ version of the code
#include <cmath>
#include <array>
#include <algorithm>
struct pnt_t
{
int x, y;
pnt_t ccw90() const
{ return { -y, x }; }
double length() const
{ return std::hypot(x, y); }
pnt_t &operator -=(const pnt_t &rhs)
{
x -= rhs.x;
y -= rhs.y;
return *this;
}
friend pnt_t operator -(const pnt_t &lhs, const pnt_t &rhs)
{ return pnt_t(lhs) -= rhs; }
friend int operator *(const pnt_t &lhs, const pnt_t &rhs)
{ return lhs.x * rhs.x + lhs.y * rhs.y; }
};
int side(const pnt_t &a, const pnt_t &b, const pnt_t &p)
{
int cp = (b - a).ccw90() * (p - a);
return (cp > 0) - (cp < 0);
}
void make_ccw(std::array<pnt_t, 3> &t)
{
if (side(t[0], t[1], t[2]) < 0)
std::swap(t[0], t[1]);
}
double ncos(pnt_t a, const pnt_t &o, pnt_t b)
{
a -= o;
b -= o;
return -(a * b) / (a.length() * b.length());
}
bool inside_circle(std::array<pnt_t, 3> t, const pnt_t &p)
{
make_ccw(t);
std::array<int, 3> s =
{ side(t[0], t[1], p), side(t[1], t[2], p), side(t[2], t[0], p) };
unsigned outside = std::count(std::begin(s), std::end(s), -1);
if (outside != 1)
return outside == 0;
while (s[0] >= 0)
{
std::rotate(std::begin(t), std::begin(t) + 1, std::end(t));
std::rotate(std::begin(s), std::begin(s) + 1, std::end(s));
}
double
min_org = std::min({
ncos(t[0], t[1], t[2]), ncos(t[2], t[0], t[1]),
ncos(t[1], t[0], p), ncos(p, t[1], t[0]) }),
min_alt = std::min({
ncos(t[1], t[2], p), ncos(p, t[2], t[0]),
ncos(t[0], p, t[2]), ncos(t[2], p, t[1]) });
return min_org <= min_alt;
}
and a couple of tests with arbitrarily chosen triangles and a large number of random points
Of course, the whole thing can be easily reformulated without even mentioning Delaunay triangulations. Starting from step 4 this solution is based in the property of the opposite angles of cyclic quadrilateral, which must sum to 180°.
In this Math SE post of mine I included an equation which checks if four points are cocircular by computing a 4×4 determinant. By turning that equation into an inequality you can check for insideness.
If you want to know which direction the inequality has to go, conisder the case of a point very far away. In this case, the x²+y² term will dominate all other terms. So you can simply assume that for the point in question, this term is one while the three others are zero. Then pick the sign of your inequality so this value does not satisfy it, since this point is definitely outside but you want to characterize inside.
If numeric precision is an issue, this page by Prof. Shewchuk describes how to obtain consistent predicates for points expressed using regular double precision floating point numbers.
Given 3 points (x1,y1),(x2,y2),(x3,y3) and the point you want to check is inside the circle defined by the above 3 points (x,y) you can do something like
/**
*
* #param x coordinate of point want to check if inside
* #param y coordinate of point want to check if inside
* #param cx center x
* #param cy center y
* #param r radius of circle
* #return whether (x,y) is inside circle
*/
static boolean g(double x,double y,double cx,double cy,double r){
return Math.sqrt((x-cx)*(x-cx)+(y-cy)*(y-cy))<r;
}
// check if (x,y) is inside circle defined by (x1,y1),(x2,y2),(x3,y3)
static boolean isInside(double x,double y,double x1,double y1,double x2,double y2,double x3,double y3){
double m1 = (x1-x2)/(y2-y1);
double m2 = (x1-x3)/(y3-y1);
double b1 = ((y1+y2)/2) - m1*(x1+x2)/2;
double b2 = ((y1+y3)/2) - m2*(x1+x3)/2;
double xx = (b2-b1)/(m1-m2);
double yy = m1*xx + b1;
return g(x,y,xx,yy,Math.sqrt((xx-x1)*(xx-x1)+(yy-y1)*(yy-y1)));
}
public static void main(String[] args) {
// if (0,1) is inside the circle defined by (0,0),(0,2),(1,1)
System.out.println(isInside(0,1,0,0,0,2,1,1));
}
The method for getting an expression for the center of circle from 3 points goes from finding the intersection of the 2 perpendicular bisectors of 2 line segments, above I chose (x1,y1)-(x2,y2) and (x1,y1)-(x3,y3). Since you know a point on each perpendicular bisector, namely (x1+x2)/2 and (x1+x3)/2, and since you also know the slope of each perpendicular bisector, namely (x1-x2)/(y2-y1) and (x1-x3)/(y3-y1) from the above 2 line segments respectively, you can solve for the (x,y) where they intersect.

PyCUDA - passing a matrix by reference from python to C++ CUDA code

I have to write in a PyCUDA function that gets two matrices Nx3 and Mx3, and return a matrix NxM, but I can't figure out how to pass by reference a matrix without knowing the number of columns.
My code basically is something like that:
#kernel declaration
mod = SourceModule("""
__global__ void distance(int N, int M, float d1[][3], float d2[][3], float res[][M])
{
int i = threadIdx.x;
int j = threadIdx.y;
float x, y, z;
x = d2[j][0]-d1[i][0];
y = d2[j][1]-d1[i][1];
z = d2[j][2]-d1[i][2];
res[i][j] = x*x + y*y + z*z;
}
""")
#load data
data1 = numpy.loadtxt("data1.txt").astype(numpy.float32) # Nx3 matrix
data2 = numpy.loadtxt("data2.txt").astype(numpy.float32) # Mx3 matrix
N=data1.shape[0]
M=data2.shape[0]
res = numpy.zeros([N,M]).astype(numpy.float32) # NxM matrix
#invoke kernel
dist_gpu = mod.get_function("distance")
dist_gpu(cuda.In(numpy.int32(N)), cuda.In(numpy.int32(M)), cuda.In(data1), cuda.In(data2), cuda.Out(res), block=(N,M,1))
#save data
numpy.savetxt("results.txt", res)
Compiling this I receive an error:
kernel.cu(3): error: a parameter is not allowed
that is, I cannot use M as the number of columns for res[][] in the declaretion of the function. I cannot either left the number of columns undeclared...
I need a matrix NxM as an output, but I can't figure out how to do this. Can you help me?
You should use pitched linear memory access inside the kernel, that is how ndarray and gpuarray store data internally, and PyCUDA will pass a pointer to the data in gpu memory allocated for a gpuarray when it is supplied as a argument to a PyCUDA kernel. So (if I understand what you are trying to do) your kernel should be written as something like:
__device__ unsigned int idx2d(int i, int j, int lda)
{
return j + i*lda;
}
__global__ void distance(int N, int M, float *d1, float *d2, float *res)
{
int i = threadIdx.x + blockDim.x * blockIdx.x;
int j = threadIdx.y + blockDim.y * blockIdx.y;
float x, y, z;
x = d2[idx2d(j,0,3)]-d1[idx2d(i,0,3)];
y = d2[idx2d(j,1,3)]-d1[idx2d(i,1,3)];
z = d2[idx2d(j,2,3)]-d1[idx2d(i,2,3)];
res[idx2d(i,j,N)] = x*x + y*y + z*z;
}
Here I have assumed the numpy default row major ordering in defining the idx2d helper function. There are still problems with the Python side of the code you posted, but I guess you know that already.
EDIT: Here is a complete working repro case based of the code posted in your question. Note that it only uses a single block (like the original), so be mindful of block and grid dimensions when trying to run it on anything other than trivially small cases.
import numpy as np
from pycuda import compiler, driver
from pycuda import autoinit
#kernel declaration
mod = compiler.SourceModule("""
__device__ unsigned int idx2d(int i, int j, int lda)
{
return j + i*lda;
}
__global__ void distance(int N, int M, float *d1, float *d2, float *res)
{
int i = threadIdx.x + blockDim.x * blockIdx.x;
int j = threadIdx.y + blockDim.y * blockIdx.y;
float x, y, z;
x = d2[idx2d(j,0,3)]-d1[idx2d(i,0,3)];
y = d2[idx2d(j,1,3)]-d1[idx2d(i,1,3)];
z = d2[idx2d(j,2,3)]-d1[idx2d(i,2,3)];
res[idx2d(i,j,N)] = x*x + y*y + z*z;
}
""")
#make data
data1 = np.random.uniform(size=18).astype(np.float32).reshape(-1,3)
data2 = np.random.uniform(size=12).astype(np.float32).reshape(-1,3)
N=data1.shape[0]
M=data2.shape[0]
res = np.zeros([N,M]).astype(np.float32) # NxM matrix
#invoke kernel
dist_gpu = mod.get_function("distance")
dist_gpu(np.int32(N), np.int32(M), driver.In(data1), driver.In(data2), \
driver.Out(res), block=(N,M,1), grid=(1,1))
print res

c++ program can you help me

I need code to The solution of this problems Use Microsoft Visual Studio 6.0
Problem 1:
Write a complete C++ program that takes five floats A, B, C, D, and E and reorders them such that the smallest number is stored in A, and the largest number in E. Assume that the Five numbers are distinct (different). The program reads five floats from the keyboard then reorder them. The program should then print the values of A, B, C, D, and E after the Reorder.
Problem 2:
Write a C++ program that reads in one of two characters input by the user. If the user input C, the program should calculate the area of a circle of radius input by the user. If the user inputs R, the program calculates the area of the rectangle of width and length input by the user.
Problem 3:
Write a C++ program that finds the roots of a second order equation (if they exist).
The equation will be:
a(X^2)+bX+c, the user will input the coefficients a, b, c. The program will first determine if the equation has roots or not. If it does, then the program will find these roots and display to the user:
a(X^2)+bX+c=(X-R1)+(X-R2) where R1 and R2 are the roots of the equation.
First program:
#include <iostream>
using namespace std;
int main (int argc, const char * argv[])
{
float A,B,C,D,E;
float b,c,d,e;
cout<<"This program takes 5 float inputs,reorder then print them";
cout<<"\n Enter the first float";
cin>>A;
cout<<"\n Enter the first float";
cin>>b;
if (b>A){
B=A;
A=b;
}
else B=b;
cout<<"\n Enter the second float";
cin>>c;
if (c>A){
C=B;
B=A;
A=c;
}
else if (c>B){
C=B;
B=c;
}
else C=c;
cout<<"\n Enter the third float";
cin>>d;
if (d>A){
D=C;
C=B;
B=A;
A=d;
}
else if (d>B){
D=C;
C=B;
B=d;
}
else if(d>C){
D=C;
C=d;
}
cout<<"\n Enter the fourth float";
cin>>e;
if(e>A){
E=D;
D=C;
C=B;
B=A;
A=e;
}
else if(e>B){
E=D;
D=C;
C=B;
B=e;
}
else if(e>C){
E=D;
D=C;
C=e;
}
else if(e>D){
E=D;
D=e;
}
cout<<A<<"\t"<<B<<"\t"<<C<<"\t"<<D<<"\t"<<E;
return 0;
}

Resources