Equation returning 1.#QO - c

I've tried searching for anything similar about my issue on several websites, including this one, but none I've found so far are similar. After searching about the term 1.#QO, I found something about quiet NaN, but I'm new to C in general, so I don't really understand the issue .
I'm trying to take the x and y values of a joystick, and when then use a formula for distance to find the distance between the joystick's position, and the joystick's natural resting position (0,0).
If it matters, I'm trying to do this in RobotC.
#pragma config(Hubs, S1, HTMotor, none, none, none)
#pragma config(Sensor, S1, , sensorI2CMuxController)
#pragma config(Motor, mtr_S1_C1_1, DriveMotor, tmotorTetrix, openLoop)
//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//
#include "JoystickDriver.c"
int calculateDrivePower(int joyStickX, int joyStickY)
{
if (joyStickX != 0 & joyStickY != 0)
{
int joyDistance = (sqrt(pow((joyStickX - 0),2)+ pow((-joyStickY - 0),2)));
joyDistance = ((joyDistance/127)*100);
return (joyDistance);
}
else
{
return 0;
}
}
task main()
{
int previousJoySlope = 0;
int TurnSpeed = 70;
while (true)
{
getJoystickSettings(joystick);
if (abs(joystick.joy1_x1) > 10 || abs(joystick.joy1_y1) > 10)
{
writeDebugStreamLine("Test successful.");
motor[DriveMotor] = calculateDrivePower(joystick.joy1_x1,joystick.joy1_y1);
}
}
}
If anyone could provide any insight, that'd be fantastic, thanks.

if (joyStickX != 0 & joyStickY != 0)
{
int joyDistance = (sqrt(pow((joyStickX - 0),2)+ pow((-joyStickY - 0),2)));
joyDistance = ((joyDistance/127)*100);
return (joyDistance);
}
The first issues that appears is the conditional within the if statement. The you have a single & that most likely should be &&:
if (joyStickX != 0 && joyStickY != 0)
(note: likely should be is used above because you can provide a conditional using a logical & of the tests joystickx != 0, but in this case it provides the same result. In that case, I would suggest the more readable && be used)
The next part of the code is simply the vector distance between 0,0 and the present position of the joystick. Of the general form dist^2 = (x2-x1)^2 + (y2-y1)^2 in your case x1,y1 = 0,0. Taking the square root of both sides provides dist = sqrt((x2-x1)^2 + (y2-y1)^2), or in C notation:
dist = (sqrt(pow((joyStickX - 0),2)+ pow((-joyStickY - 0),2)));
Next you have a scaling applied of dist = dist * 100/127 which provides the final distance returned. Hopefully this will help you understand what the code is doing.

Related

C Physics engine

I am working on a fabric simulator at low level, I have done some work and at this point there are some points where I would appreciate help.
The input of the program is a DRF file. This is a format used in sewing machines to indicate the needles where to move.
The 2D representation is accurate, I parse the DRF info to a polyline, apply tensions and I extrude this in a openGL render.
Now I am trying to achieve the 3D ZAxis physics. I tried two methods:
1) Asuming information
First method is based on constrains about the process of manufacturing:
we only take care of the knots where a set of yarns interact and comupte z separation in this crucial points. The result is regular: good in a lot of cases but with a lot of botched jobs in order to avoid causistincs where this is not a good assumtion (for example, doing beziers, collisions in zones between this crucial points). We desist on this alternative when we saw there was a lot os causistic we would have to hardcode,probably creating aditional gliche.
2) Custom 2D Engine
The second attempt is to aprox the yarns with box colliders 2D, check collisions with a grid, and compute new Z in funcion of this. This is by far more expensive, but leads to a better results. Although, there is some problems:
The accuracy of box colliders over the yarn is not absolute ( there are ways to solve this but it would be great to read some alternatives)
There is not iterative process:
First we compute collisions pairwise, and add to each collider a list of colliding colliders. Then, we arrange this list and separate the Z axis in function of yarn's radius with center 0.The last step is to smooth the results from discrete z to a beziers or smoothing filters. This leads to another glitches.
If I extend this recomputation to all the collisions of the current collisions, I get weird results because z changes are bad propagated( maybe I am not doing good this point)
Some colliders are recomputed wrong ( first computed yarns have more posibilites to be altered for the last ones, leading on gliches)
This is the result for the secdond approach ( without recompute z's on smoothing step):
And some of the glicthes (mainly in the first yarns computed:
This is the collisions engine:
Details of bad aproximated curves:
At this point I have some questions:
Can I fix this glitches (or a great part at least)?
Glitches about bad aproximation and glitches for z recomputation
A 3D engine like ODE could do the job in a reasonable time?
If you need some specific code don't hestiate on ask for it.
EDIT: Ok, let's narrow the thing.
Yesterday I tried some open source engines without achieving good results.
500 collisions with joints are crashing the simulation. so I discard it.
My problem:
A: How I generate the yarns:
I have a set of points and I trace beziers between them.
CUBIC_BEZIER(p1x,p1y,p1z,p2x,p2y,p2z,p3x,p3y,p3z,p4x,p4y,p4z, npunts);
For each pair of points I add a collider:
p1.x = *(puntlinaux + k*NUMCOMP);
p1.y = *(puntlinaux + k*NUMCOMP + 1);
p2.x = *(puntlinaux + k*NUMCOMP + 4);
p2.y = *(puntlinaux + k*NUMCOMP + 5);
*bc = getCollider(&p1,&p2,x,y,z, radi_mm_fil , pbar->numbar);
where
BoxCollider2D getCollider(punt_st* p1, punt_st* p2, float *x, float *y, float *z, float radiFil,int numbar){
BoxCollider2D bc;
bc.numBar = numbar;
int i;
for(i = 0; i < MAX_COLLIDERS; i++) {
bc.collisions[i] = NULL;
}
bc.isColliding = 0;
bc.nCollisions = 0;
bc.nextCollider = NULL;
bc.lastCollider = NULL;
bc.isProcessed = 0;
punt_st center;
p1->x = p1->x;
p2->x = p2->x;
float distance = distancePunts_st(p1,p2);
bc.angle = atan2((p2->y - p1->y),(p2->x-p1->x));
//bc.angle = 0;
//DEBUG("getCollider\n");
//DEBUG("angle: %f, radiFil: %f\n", bc.angle*360/(2*3.141592), radiFil);
//DEBUG("Point: pre [%f,%f] post:[%f,%f]\n", p1->x, p1->y, p2->x, p2->y);
p1->y = p1->y;
p2->y = p2->y;
bc.r.min = *p1;
bc.r.max = *p2;
center = getCenterRect(bc.r);
bc.r.max.x = (center.x - distance/2);
bc.r.max.y = (center.y + radiFil) - 0.001f;
bc.r.min.x = (center.x + distance/2);
bc.r.min.y = (center.y - radiFil) + 0.001f;
bc.xIni= x;
bc.yIni= y;
bc.zIni= z;
return bc;
}
Then I add the collider to a grid to reduce complexity on comparisons
and check the collisions with Separated Axis Theorem
DEBUG("calc_sapo: checking collisions\n");
checkCollisions();
After that, I resolve the collisions leading on a discrete z aproximation.
DEBUG("calc_sapo: solving collisions\n");
resolveCollisions();
And then I apply a smooth function. This is the point where I am lost.
DEBUG("smoothing yarns\n");
smoothYarns();
To keep it simple, let's assume smoothYarns() does a simple mean value with the last and next z value:
for each collider of each yarn:
float aux = (*bc->zIni + *(bc-1)->zIni + *nextBC->zIni)/3;
float diff = aux - *bc->zIni;
*bc->zIni = aux;
Then we have to update all the colliders in contact with this recomputed collider:
void updateCollider(BoxCollider2D *bc, float diff){
int i ;
for(i = 0; i < bc->nCollisions; i++){
*bc->collisions[i]->zIni += diff;
}
}
This last step is messing up all the simulation because z's are accumulating theirselves ...
I want to know why this does not tend to converge as I expected and possible solutions for this problem.
EDIT2:
This is the algorithm that detects collisions:
For each collider in the grid position
Compare with others in the grid
if colliding: add the colliding collider to the current collider
For each yarn:
Go trhough all the colliders (linked list)
For each collider from a yarn:
Bubble sort collision yarns in function of their z order
Compute z based on yarns radius (centered on 0)
float computeZ(BoxCollider2D *array[], int nYarns, BoxCollider2D *bc){
int i, antBar;
float radiConflicte = 0;
float zMainYarn;
finger_st *pfin;
antBar = -1;
for(i = 0; i<nYarns; i++){
if(pfin != array[i]->pfin){
float radiFil = getRadiFromBC2D(*array[i]); // veure getCollider
radiConflicte += radiFil;
pfin = array[i]->pfin;
}
}
antBar = -1;
pfin = NULL;
for(i = 0; i<nYarns; i++){
float radiFil = getRadiFromBC2D(*array[i]); // veure getCollider
if(pfin != array[i]->pfin){
radiConflicte -= radiFil;
*(array[i]->zIni) = radiConflicte;
if(array[i] == bc) zMainYarn = *(array[i]->zIni);
radiConflicte -= radiFil;
pfin = array[i]->pfin;
}
else *(array[i]->zIni) = *(array[i-1]->zIni);
}
This leads in a approach where the last yarns processed can alter the firsts ones, and, in last instance, to glitches.
How I can avoid that?
Thanks a lot!

While loop not working with bool statements in C (beginner!)

I'm learning the basics right now and am making a simple game using a basic graphics library provided by my uni.
There is a projectile thrown (the path of which is drawn)
an obstacle (a wall) - which the projectile can't pass through so must go over
and a target (must also appear solid so line stops being drawn when it is hit)
Right now my projectile is being thrown right through the wall
The issue is with the while loop
Any conditions I add (after (y_displacement < FLOOR_HEIGHT)) have had no effect
(This projectile on its own stops drawing when y_displacement => FLOOR_HEIGHT (Y-Axis is inverted), but any addition of bool statements or attempts at using bool (after #including too) to stop the projectile line being drawn don't make any changes.
TRIED BOOL FOR WALL (doesn't change anything):
bool hit_wall = false;
while ((y_displacement < FLOOR_HEIGHT) && (hit_wall == false))
{
time = (x_displacement - X_HAND) / x_velocity; //speed = distance/time
y_displacement = (Y_HAND - y_velocity * time) - (GRAVITY * pow(time, 2)/2);
GFX_DrawLineTo(x_displacement, y_displacement, 3);
x_displacement += 1;
if ((x_displacement == (X_MAX/2.5)) && ((y_displacement > (Y_MAX/2))))
{
hit_wall = true;
}
}
}
If I can manage to sort this out then I should be able to do the same for my target..
Is there something wrong with what I'm doing?
BACKGROUND:
The full function is this:
void throwBall(int(x_position), int(y_position))
{
GFX_SetColour(YELLOW);
int x_mouse;
int y_mouse;
int x_distance;
int y_distance;
double angle;
float initial_velocity;
float x_velocity;
float y_velocity;
float time;
GFX_MoveTo(X_HAND, Y_HAND);
GFX_GetMouseCoordinates(&x_mouse, &y_mouse);
x_distance = x_mouse - X_HAND;
y_distance = y_mouse - Y_HAND;
angle = getAngle(x_distance, y_distance);
initial_velocity = sqrt(pow(x_distance, 2) + pow(y_distance, 2));
//these have been divided by 5 as the magnitude was too large for the window
y_velocity = (initial_velocity * sin (angle) - GRAVITY * time)/(X_MAX/256);
x_velocity = (initial_velocity * cos (angle))/(X_MAX/256);
float y_displacement;
float x_displacement;
x_displacement = X_HAND;
y_displacement = Y_HAND;
bool hit_wall = false;
while ((y_displacement < FLOOR_HEIGHT) && (hit_wall == false))
{
time = (x_displacement - X_HAND) / x_velocity; //speed = distance/time
y_displacement = (Y_HAND - y_velocity * time) - (GRAVITY * pow(time, 2)/2);
GFX_DrawLineTo(x_displacement, y_displacement, 3);
x_displacement += 1;
if ((x_displacement == (X_MAX/2.5)) && ((y_displacement > (Y_MAX/2))))
{
hit_wall = true;
}
}
}
if ((x_displacement == (X_MAX/2.5)) && ((y_displacement > (Y_MAX/2))))
{
hit_wall = true;
}
you use flaot values, and due to some reasons (values are aprroximatelly) you almost never get in this if.
you should use >, >=, < , <= poerators, but it also will not help you in 100% of cases.
best choice will be to use epsilon (Observational error, Neighbourhood)
like
float eps = 0,0000001f;
if ( abs(x_displacement - (X_MAX/2.5) ) < eps
&& y_displacement > ( (Y_MAX/2) - eps ) )
{
hit_wall = true;
}
expanding on previous answers regarding floating point equivalence and round off error, another way to do it is multiply your float or double value by some factor of 10 to move the decimal point to the right, then cast it to an int or long it. Then you can do a boolean comparison which will be on integers which will work reliably. I mention this because it can sometimes be easier to code and also read easier than doing the epilson method (which you would also have to do an absolute value on) described in the other answer .
The big thing to recognize is the factor of 10 by which you multiply with or set epsilon to.
Do not go crazy and multiply by something like 1e9 or set epsilon = 1e-9 when you don't need to because that can re-introduce the same problem.
For example if your variables for distance are in meters then you need to recognize you do not need resolution greater than ???. Let's use 1/100 of a millimeter as an example... as far as you are concerned 1.230012345mm == 1.230456789mm. So then multiply by 1e5 then cast to int or do epsilon=1e-5;. Same principle applies for units of inches, you typically do not need resolution greater than 0.0001" for anything so multiply by 1e4 or epsilon = 1e-4.
/* example */
# define D2I 1e2 /* dbl to int factor, 0.01mm resolution */
double x_displacement; /* units of millimeters for this example*/
double y_displacement; /* units of millimeters for this example*/
/* whatever previous calculations result in...
x_displacement having value of 3.00000249687738566
y_displacement having value of 120.00000085639820699
out past 6 or so decimal places a float or double will have arbitrary numbers, so don't multiply by some huge 1e12 number
*/
if ( ( (int)(x_displacement * D2I) == (int)((X_MAX / 2.5) * D2I ) ) &&
( (int)(y_displacement * D2I ) > (int)((Y_MAX / 2 ) * D2I ) )
)
{
hit_wall = true;
}

Alternative syntax of combining multiple condition check

I am implementing a simple if statement in c, where I am comparing the value of integer 'tile' to four other integers: w, a, s and d.
Here is my code:
if(tile == w || tile == a || tile == s || tile == d )
{
printf("legal\n");
return true;
}
While the above is correct, the syntax is tiresome. Is there a more elegant way of writing the condition "'tile' is one of the following integers..."
I'm a novice in programming so I apologise as I suspect the answer is very obvious. I've failed to find it addressed elsewhere though.
While eyalm's answer is maybe the one you're looking for, just wanted to chime in to point you to a more important factor here (as you mentioned, "I'm a novice in programming"), which is "Write code which is easier for humans to understand".
While the bitwise approach is shorter, it generally appears to be more difficult to understand a maintain, as it grows.
A cleaner approach will be (while it takes more effort to write the code), stick to the if ( a || b || c) syntax, or a fall-though switch case. It gives better readability.
In case your options grows longer (that you may need a horizontal scroll bar), you can consider adding a function to get the required value checked and use the return value in the condition in the if statement.
The bottom line is, there is no right or wrong way, only choose the way which make the code more readable and maintainable.
Two options i can think of...
bitwise
#define TILE_W 0x0001
#define TILE_A 0x0002
#define TILE_S 0x0004
#define TILE_D 0x0008
if (tile&(TILE_w|TILE_A|TILE_S|TILE_D))
{
printf("legal\n");
return true;
}
switch-case
switch (tile)
{
case w:
case a:
case s:
case d:
printf("legal\n");
return true;
default:
return false;
}
Solution for improvement can depend on values which you compare with.
If w, a, s and d are integer numbers that have consecutive values (e.g. 10, 11, 12 and 13), if-statement can use condition for boundaries:
if( tile >= w && tile <= d) { printf("legal\n"); }
If values are disparate (e.g. 6, 32, 142, 55), you can use switch..case construction, like
switch (tile)
{
case w:
case a:
case s:
case d:
printf("legal\n");
break;
default:
printf("ILLEGAL\n");
break;
}
Also you can use setting flag in one or multiple if as
int legal = 0;
// checking can be in different places of code
if (tile == w)
legal = 1;
if (tile == a || tile == s)
legal = 1;
if (tile == d)
legal = 1;
if( legal )
{
printf("legal\n");
}
And consider storing w, a, s and d values as array of valid values, so loop can be used for checking:
int valArr[] = {101, 151, 333, 7}; // you can add any number of values here
int i;
int legal = 0;
for(i = 0; i < ( sizeof(valArr)/sizeof(valArr[0]) ); i++)
{
if(valArr[i] == tile)
{
legal = 1;
break;
}
}
if( legal )
{
printf("legal\n");
}
else
{
printf("ILLEGAL\n");
}

C program shows no error but doesn't show output

Roy wants to change his profile picture on Facebook. Now Facebook has some restriction over the dimension of picture that we can upload.
Minimum dimension of the picture can be L x L, where L is the length of the side of square.
Now Roy has N photos of various dimensions.
Dimension of a photo is denoted as W x H
where W - width of the photo and H - Height of the photo
When any photo is uploaded following events may occur:
If any of the width or height is less than L, user is prompted to upload another one. Print "UPLOAD ANOTHER" in this case.
If width and height are both large enough and
(a) if the photo is already square then it is accepted. Print "ACCEPTED" in this case.
(b) else user is prompted to crop it. Print "CROP IT" in this case.
Code:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int len; /* len is the length of the side of square */
scanf("%d",&len);
int test;
scanf("%d",&test);
while(test--)
{
int w,h;
/* w - width of the photo and h- Height of the photo */
scanf("%d %d",&w,&h);
if(w==len && h==len)
{
printf("ACCEPTED\n");
}
else if(w>len || w==len && h>len || h==len)
{
printf("CROP IT\n");
}
else
{
printf("UPLOAD ANOTHER\n");/* print */
}
}
return 0;/* success */
}
If your problem is that you're seeing no output at all, it's likely because it's running in an IDE and the output window is closing before you can see it. Judicious use of a getchar() at the end of main() may be all you need to fix this, though I'd probably prefer to just run it from the command line.
In any case, since && has a higher precedence than ||, your second condition is effectively:
else if ((w > len) || (w == len && h > len) || (h == len))
which is clearly wrong since having a photo with width more than what was necessary would result in a request for cropping regardless of the other sub-conditions.
You would be better off following the textual specs more closely so that you can actually check it more easily. That would entail something like (with slightly simplified specs still meeting the original intent):
If any of the width or height is less than L, user is prompted to upload another one.
Otherwise both are large enough. If the photo is already square then it is accepted.
Otherwise user is prompted to crop it.
The code for that is a much simpler:
if ((w < len) || (h < len)) {
puts ("UPLOAD ANOTHER");
} else if (h == w) { // Both large enough otherwise previous
puts ("ACCEPTED"); // condition would have been true.
} else {
puts ("CROP IT");
}
Due to operator precedence,
else if(w>len || w==len && h>len || h==len)
is equivalent to:
else if(w>len || (w==len && h>len) || h==len)
What you need to use is:
else if( (w>len || w==len) && (h>len || h==len) && (w == h) )
You can simplify that to:
else if( w >= len && h >= len && w == h )
which can be further simplified to:
else if( w >= len && w == h )
It will show output but the program runs faster than you expect. It will close as soon as the output is displayed . It will not wait till you read it.
So use getch(); declared in conio.h to get a single key press as input after you have printed all the output (right before the return statement. It will make the program wait for the user to press a key before exiting.
here is the screenshot. it is running without error on me.
NOTE: This is not an answer. But this is just the only way to give picture example :) no need to up
Maybe you only need to put getchar(); at the end of the code before return to let the screen to pause for a while. it is just exiting very fast

Slot Machine Game In C - Printing Reels Issue

I'm trying to create a small slot-machine game that has three reels and four possible symbols for each reel (bell, orange, cherry, and horse).
I started by generating a random value between 1-4 and now I'm trying to get the first reel to print out the text associated with the generated values.
Here is the code, I hope someone can help and point out why it doesn't work and how I can fix it. From the code below I was expecting the program to print out 3 different pieces of text that were associated with the generated numbers but instead "Cherry" prints out three times.
// Generates 3 different random values between 1-4 and stores them within the slotVal array.
int slotVal[3], counter;
srand(time(NULL));
for (counter = 0; counter < 3; counter++) {
slotVal[counter] = rand() % 4 + 1;
}
// Checks generated values and prints associated text.
for (counter = 0; counter < 3; counter++) {
if (slotVal[counter] = 1) {
printf("Cherry");
}
else if (slotVal[counter] = 2) {
printf("Bell");
}
else if (slotVal[counter] = 3) {
printf("Orange");
}
else
printf("Horseshoe");
}
Your if statements are wrong, you are assigning(=) not comparing(==):
// Checks generated values and prints associated text.
for (counter = 0; counter < 3; counter++) {
if (slotVal[counter] == 1) {
printf("Cherry");
} else if (slotVal[counter] == 2) {
printf("Bell");
} else if (slotVal[counter] == 3) {
printf("Orange");
} else {
printf("Horseshoe");
}
}
If you do if(something = 1) the condition evaluated will be the 1 because the assignment operator returns the assigned variable. Since 1 evaluates to true, your first condition would be met and the other else blocks would be ignored.
Some useful tips to avoid this particular error are:
Do if(1 == variable) instead of if(variable == 1), because the first raises a compilation (if you only use one = sign) error and the second doesn't;
Define a name for the comparison, for example: #define EQUALS == which will allow you to do if(variable EQUALS 10)
When you program in C, always enable all compiler warnings that you can find. C is not a beginner-friendly language, and it provides you with plenty of ways to shoot yourself in the foot. Enabling compiler warnings protects against a few of these ways.
When you use GCC, at least enable the -Wall -Wextra warnings. They will warn you that in the if conditionals, you are using the assignment operator = instead of the comparison operator ==.

Resources