Translation from python to c++

I have a question about translating code from python to C++. I translated a program in C++ and ckecked it 10 times. What should I do if everything is correct syntactically, because the program is compiling but it's not the same result the python program displays? I also checked the logic of the program 20 times. Is there a solution?

It is a program from a book by John Zelle, which in C++ is very similar to the version in Python. It would be a problem to post it here.

Any ideas?
Last edited on
Without seeing the two sources, if the two programs produce different results then your "translation" is probably defective.

But if you want anything other than a "WAG" you're going to need to post the code to both programs along with a description of the purpose of the "original" program.

Debug! Use the debugger to trace through the C++ program and see where what is happening deviates from what is expected - the values of variables, the path taken through the code etc etc.

I don't know Python, but in C++ array bounds start at 0 and not 1. Also in C++ if you divide an integer by an integer the result is an integer irrespective of the type the result is assigned.

1
2
3
int a = 7;

double b = a / 2;


b is 3, not 3.5 as might be expected. To get 3.5 you should use:

 
double b = a / 2.0;


ie specify 2 as a double, not an int.
there are a couple of things python does oddly.
first, it does not appear to have an integer type, but rather a linked list of bytes or something that represent a large integer, which is exceedingly slow but more interestingly, you cannot overflow. So for example a factorial program in c++ can only go to a smallish input before it overflows a 32 or 64 bit integer, while python just crafts a 128 bit int or a 256 bit int and keeps going.

just post the code. its your code, at this point, if you did the translation, so its yours to post. Assuming that code in most books is smallish, it should also be fair use to post a translation of it.

also, how different are the results? If it is a floating point calculation and its off by a tiny bit, that may just be differences in how the expressed code is turned into executable commands.

if the worst comes to worst, compare the assembly generated by both? Does python provide this or is it too far removed from the computer?
Last edited on
@OP
Zelle book name, edition, page ref would be good.
I found the source code on the internet so I don't have to find the book of John Zelle.

https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwjs6LvK1tHrAhWRfMAKHS4ABfkQFjADegQIAhAB&url=http%3A%2F%2Fanh.cs.luc.edu%2F150s06%2Fprivate%2Fzelle_code%2Fchapter09%2Frball.py&usg=AOvVaw20bu7VBueQAawBissNlg0Q

But if someone has it, the source code should be on page 300.

Download link can be found here.

https://computingsavvy.com/books/free-download-python-programming-an-introduction-to-computer-science-3rd-edition/


There are several problems with sources from the internet, for example, the program at that link is not well transcripted. Print() function needs attention.


I changed the program not to use functions, except for the printIntro() function.

The problem seems to be where it simulates a single game and calculates scoreA and scoreB. because it calculates winsA and winsB based on the scores.


If I use probA and probB 0.6 and 0.65 inside the python program, winsA=33 and winsB=67.

In C++ is not the same, it is a big difference.

I thought that this program can't be translated in C++ to return the same result because if I use the same functions as in the python program and pointers to return multiple values, the result is the same as in this program that I will post here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145

#include <iostream>
#include <cstdlib>
#include <time.h>

using namespace std;

#define newline "\n"


void printIntro();

void printIntro() {

cout << "This program simulates a game of raquetball between two " << newline; 

cout << "players called 'A' and 'B'. The ability of each player is " << newline;

cout << "indicated by a probability (a number between 0 and 1) that " << newline;

cout << "the player wins the point when serving.Player A always " << newline;

cout << "has the first serve"; }



int main(){
    
    srand(time(NULL));
    
    printIntro();


	//Enter the three simulation parameters

	float probA, probB;

	int n;

	cout << "\n What is the prob. player A wins the serve? ";

	cin >> probA;

	cout << "What is the prob player B wins the serve? ";

	cin >> probB;

	cout << "How many games to simulate? ";

	cin >> n;



	//Simulate a single game of raquetball between players whose
        //abilities are represented by the probability of winning a serve
        //Find final scores for A and B

	string serving = "A";

	int scoreA, scoreB;

	scoreA = 0;

	scoreB = 0;
	
	float number = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);

	

		
	while (!(scoreA ==15 or scoreB == 15)) {

		//currently, this program executes only 

		//the first if condition and returns control

                //to the while loop


		if (serving == "A"){

			if (number < probA) {

				scoreA = scoreA + 1;}

			else {serving = "B";} }

		else {

			if (number < probB) {

				scoreB = scoreB +1;

			}

			else {

				serving = "A";

			} } 
	}




    /*Simulate n games of raquetball between players whose
    abilities are represented by the probability of winning a serve.
    Find the number of wins between a and b*/

     int winsA, winsB;

     winsA = winsB = 0;

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


			if (scoreA > scoreB) {

				winsA = winsA + 1;

			}

			else {

				winsB = winsB + 1;

			}}


	
//print a summary of wins for each player

int ng;

ng = winsA + winsB;

cout << "\n Games simulated: " << ng << newline;

cout << "Wins for A: " << winsA << " " << winsA/ng << newline;

cout << "Wins for B: " << winsB << " " << winsB/ng;


}




Last edited on
There are some relatively minor changes but substantial one or two because you removed the function structure. However here is a version you can check that might be useful:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>

void printIntro()
{
    
    std::cout
    << "This program simulates a game of raquetball between two\n"
    << "players called 'A' and 'B'. The ability of each player is\n"
    << "indicated by a probability (a number between 0 and 1) that\n"
    << "the player wins the point when serving.Player A always\n"
    << "has the first serve\n\n";
}

int main()
{
    srand(time(NULL));
    printIntro();
    
    // Enter the three simulation parameters
    double probA{0}, probB{0};
    int n{0};
    std::cout << "What is the prob. player A wins the serve? ";
    std::cin >> probA;
    
    std::cout << "What is the prob player B wins the serve? ";
    std::cin >> probB;
    
    std::cout << "How many games to simulate? ";
    std::cin >> n;
    
    /*
     Simulate a single game of raquetball between players whose
     abilities are represented by the probability of winning a serve
     Find final scores for A and B
     */
    
    char serving = 'A';
    int scoreA{0}, scoreB{0};
    double number{0};
    
    int winsA{0}, winsB{0};
    int game_no{0};
    
    while ( (scoreA != 15) and (scoreB != 15) and (game_no != n))
    {
        /*
         currently, this program executes only
         the first if condition and returns control
         to the while loop
         */
        number =  ( rand() % 100 ) /100.;
        std::cout << number << '\n';
        
        if (serving == 'A')
        {
            if (number < probA)
                scoreA += 1;
            else
                serving = 'B';
        }
        else
        {
            if (number < probB)
                scoreB += 1;
            else
                serving = 'A';
        }
        
        if (scoreA > scoreB)
            winsA += 1;
        else
            winsB += 1;
        
        game_no++;
    }
    
    // print a summary of wins for each player
    double ng = winsA + winsB;
    
    std::cout << "Games simulated: " << ng << '\n';
    std::cout << "     Wins for A: " << winsA << ' ' << winsA/ng << '\n';
    std::cout << "     Wins for B: " << winsB << ' ' << winsB/ng << '\n';
}



I picked 1000 games but needless to say much less than that were needed as per while condition. I also got it to print out the random 'numbers'.


In C++ integer arithmetic only gives integer results so two integer a,b give zero for a/b, b non-zero of course. So your average calcalucation need to take that into account.

This program simulates a game of raquetball between two
players called 'A' and 'B'. The ability of each player is
indicated by a probability (a number between 0 and 1) that
the player wins the point when serving.Player A always
has the first serve

What is the prob. player A wins the serve? .5
What is the prob player B wins the serve? .7
How many games to simulate? 1200
0.13
0.19
0.74
0.49
0.2
0.36
0.9
0.43
0.24
0.34
0.02
0.45
0.28
0.45
0.79
0.94
0.94
0.87
0.36
0.81
0.46
0.17
0.58
0.48
0.88
0.3
0.21
0.63
0.66
0.92
0.26
0.01
0.74
0.07
0.7
0.53
0.09
0
0.37
0.37
0.37
0.51
Games simulated: 42
     Wins for A: 36 0.857143
     Wins for B: 6 0.142857
Program ended with exit code: 0
@MaRahl
In C++ is not the same, it is a big difference.

I thought that this program can't be translated in C++ to return the same result because if I use the same functions as in the python program and pointers to return multiple values, the result is the same as in this program that I will post here.


As I mentioned in my post the previous day, in C++ int / int gives an int result! This is one of the most common reasons for an 'incorrect' result from a calculation - hence why I suggested it. But it seems you ignored this and expected others to fix your code.

This result is not proportional to 1200 games.


I ran this program in python like it was modified and with the same input and got results close to 100 for winsA and close to 1000 for winsB.

(rand() % 100) / 100. needs attention

Thank you.
Last edited on
I just found that there is a fix.

Changing while ( (scoreA != 15) and (scoreB != 15) and (game_no != n)) to

while (((scoreA !=15) or (scoreB != 15)) and (game_no != n))

Now it has the same results as in the other programming language.


In my case it is proportional to 42 games
I understand that and all the reasons why it is so. Also I noticed that even changing the while loop, if the program is run with the same inputs several times , it will show results very similar to the ones that were obtained after running this program like it was modified in the first case, when you say it is proportional.

That's right.
Excellent :)
in a game of raquetball both players start at 0 points
the player that reaches 15 points wins the game

1
2
3
4
5
6
7
8
9
10
11
//simulate n games
for(int game_no = 0; game_no < n; ++game_no){
   scoreA = scoreB = 0;

   //here goes the code to simulate one game

   if (scoreA > scoreB) //or if (scoreA==15)
      ++winsA;
   else
      ++winsB;
}
againtry's code does not simulate `n' games, it simulates one game with at most `n' serves
it also counts a win for A if it is ahead on points
for example
scoreA = 0, scoreB = 0, winsA = 0, winsB = 0
A serves, A scores
scoreA = 1, scoreB = 0, winsA = 1, winsB = 0
A serves, A scores
scoreA = 2, scoreB = 0, winsA = 2, winsB = 0
A serves, B scores
scoreA = 2, scoreB = 0, winsA = 3, winsB = 0
B serves, B scores
scoreA = 2, scoreB = 1, winsA = 4, winsB = 0
B serves, B scores
scoreA = 2, scoreB = 2, winsA = 4, winsB = 1
¿does that make sense to you?


then we have your «fix» while (((scoreA != 15) or (scoreB != 15)) and (game_no != n))
let's break it
1
2
3
4
while(
	(scoreA != 15 or scoreB != 15) //false only when scoreA = scoreB = 15, quite unlikely
	and game_no != n //so this is the only one that matters
)
bother yourself and check the value of scoreA and scoreB, they both likely are quite over 15


> I changed the program not to use functions
¿why?

you may return multiple values in c++, but that's not really needed here. you don't actually care about the scores, just who won each game
Last edited on
Topic archived. No new replies allowed.